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

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

大家好,我是【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接口

  1. public interface UserDao {
  2. List<User> findAll() throws IOException;
  3. }

2. 编写映射文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="userMapper">
  6. <select id="findAll" resultType="user">
  7. select * from user
  8. </select>
  9. </mapper>

3. 编写UserDaoImpl实现

  1. public class UserDaoImpl implements UserDao {
  2. @Override
  3. public List<User> findAll() throws IOException {
  4. //加载核心配置文件
  5. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  6. //获得sqlSession工厂对象
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. //获得sqlSession对象
  9. SqlSession session = sqlSessionFactory.openSession();
  10. //执行sql语句
  11. List<User> userList = session.selectList("userMapper.findAll");
  12. session.close();
  13. return userList;
  14. }
  15. }

使用代理的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的类型相同


一一对应

测试

  1. @Test
  2. public void proxyTest() throws IOException {
  3. InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. //获得MyBatis框架生成的UserMapper接口的实现类
  7. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  8. List<User> userList = mapper.findAll();
  9. System.out.println(userList);
  10. }

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

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

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

相关文章