• Java -- MyBatis学习笔记5、getMapper


    1、为什么要使用Dao代理来实现CURD?

    观察笔记4可以发现、在传统Dao层开发模式中、Dao接口实现类并没有干什么实质性的工作,它仅仅就是通过SqlSession的相关API、根据用户提供的命名空间和id值、定位到映射mapper文件中相应的SQL语句,真正对DB进行操作的工作其实是由框架通过mapper中的SQL完成的。

    • 所以

    MyBatis框架就抛开了 Dao的实现类,直接定位到映射文件mapper中的相应SQL语句,对DB进行操作。这种对Dao的实现方式称为Mapper的动态代理方式。Mapper动态代理方式无需程序员实现 Dao 接口。接口是由 MyBatis 结合映射文件自动生成的动态代理实现的。

    2、在MyBatis中如何使用代理、直接找到对应的mapper文件?

    • 首先、将接口实现类删除。既然使用代理直接找到接口对应的mapper文件了,所以就不需要接口实现类了。
    • 通过SqlSession调用getMapper()即可获取指定接口的实现类对象。该方法的参数为指定Dao接口类的class值。

    3、代码实现:

    • 直接对上一笔记的测试类代码进行修改、首先还是声明dao接口和sqlSession对象、然后在方法里给对象赋值、如下:
        private UserInfoDao userInfoDao;
        private SqlSession sqlSession;
        @Before
        public void init() throws IOException
        {
            this.sqlSession = MyBatisUtils.getSqlSession();
            this.userInfoDao = this.sqlSession.getMapper(UserInfoDao.class);
        }
        @After
        public void finish()
        {
            //关闭selectList,释放资源
            this.sqlSession.close();
        }
    
    • 增删改查修改如下:
    @Test
        public void selectAll()
        {
            List<UserInfo> userList = userInfoDao.selectAll();
            //循环输出集合中的结果
            userList.forEach(x -> System.out.println(x));
        }
        @Test
        public void selectUser()
        {
            UserInfo userInfo = this.userInfoDao.selectUser(2);
            System.out.println(userInfo);
        }
    
        @Test
        public void insert()
        {
            UserInfo userInfo = new UserInfo();
            userInfo.setName("王昭君");
            userInfo.setAge(16);
            int result = this.userInfoDao.insert(userInfo);
            sqlSession.commit();
            System.out.println(result);
        }
    
        @Test
        public void update()
        {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(2);
            userInfo.setName("李白");
            userInfo.setAge(20);
            int result = this.userInfoDao.update(userInfo);
            sqlSession.commit();
            System.out.println(result);
        }
    
        @Test
        public void delete()
        {
            int result = this.userInfoDao.delete(6);
            sqlSession.commit();
            System.out.println(result);
        }
    

    这样、通过代理的方式、直接找到对应的mapper文件里的标签和语句,更直接简单和简洁。

  • 相关阅读:
    P4342 [IOI1998]Polygon
    P1194 买礼物
    P1363 幻想迷宫
    Installing Wine 1.5: configure: error: Cannot build a 32-bit program, you need to install 32-bit development libraries(转载)
    Linux系统调用之open(), close() (转载)
    undefined reference to 'pthread_create'问题解决(转载)
    linux中的C里面使用pthread_mutex_t锁(转载)
    #if、#ifdef、#if defined之间的区别(转载)
    linux下解压tgz文件(转载)
    linux修改用户主目录的方法 (转载)
  • 原文地址:https://www.cnblogs.com/dcy521/p/14745940.html
Copyright © 2020-2023  润新知