【重温SSM框架系列】12 - Mybatis中dao层的实现

x33g5p2x  于2022-04-10 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(234)

大家好,我是【1+1=王】, 热爱java的计算机(人工智能)渣硕研究生在读。
如果你也对java、人工智能等技术感兴趣,欢迎关注,抱团交流进大厂!!!
Good better best, never let it rest, until good is better, and better best.

近期会重新温习一下SSM的相关知识,相应的博客会更新至专栏【SSM框架】中,欢迎大家关注!
SSM专栏:https://blog.csdn.net/weixin_43598687/category_11652306.html

传统方式实现

1. 编写UserDao接口

public interface UserDao {
    List<User> findAll() throws IOException;
}

2. 编写映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="userMapper">
    <select id="findAll" resultType="user">
        select * from user
    </select>
</mapper>

3. 编写UserDaoImpl实现

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() throws IOException {
        //加载核心配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //获得sqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获得sqlSession对象
        SqlSession session = sqlSessionFactory.openSession();
        //执行sql语句
        List<User> userList = session.selectList("userMapper.findAll");

        session.close();
        
        return userList;
    }
}

使用代理的dao层实现

Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper 接口开发需要遵循以下规范:

  1. Mapper.xml文件中的namespace与mapper接口的全限定名相同
  2. Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
  3. Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
  4. Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同


一一对应

测试

@Test
    public void proxyTest() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获得MyBatis框架生成的UserMapper接口的实现类
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.findAll();

        System.out.println(userList);
    }

SSM专栏:https://blog.csdn.net/weixin_43598687/category_11652306.html

《新程序员》:云原生和全面数字化实践

50位技术专家共同创作,文字、视频、音频交互阅读

相关文章