zoukankan      html  css  js  c++  java
  • Mapper动态代理方式

    开发规范

     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的类型相同

     

    遵循以上规范创建Mapper接口即可替代原始的Dao与DaoImpl的方式。

    因为可以直接从sqlSession中获取Mapper接口的代理对象(相当于帮你生成了实现类,但返回的还是个接口)

    @Test
        public void testGetUserById() {
            // 获取sqlSession,和spring整合后由spring管理
            SqlSession sqlSession = this.sqlSessionFactory.openSession();
    
            // 从sqlSession中获取Mapper接口的代理对象(相当于SqlSession帮我生成了实现类,但返回的还是个接口)
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            // 执行查询方法
            User user = userMapper.getUserById(1);
            System.out.println(user);
    
            // 和spring整合后由spring管理
            sqlSession.close();
        }

    小结

    ♦selectOne和selectList

    动态代理对象调用sqlSession.selectOne()和sqlSession.selectList()是根据mapper接口方法的返回值决定,如果返回list则调用selectList方法,如果返回单个对象则调用selectOne方法。

    ♦namespace

    mybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。

  • 相关阅读:
    将vue文件script代码抽取到单独的js文件
    git pull 提示错误:Your local changes to the following files would be overwritten by merge
    vue和uniapp 配置项目基础路径
    XAMPP Access forbidden! Access to the requested directory is only available from the local network.
    postman与newman集成
    postman生成代码段
    Curl命令
    POST方法的Content-type类型
    Selenium Grid 并行的Web测试
    pytorch转ONNX以及TnesorRT的坑
  • 原文地址:https://www.cnblogs.com/xk920/p/9811183.html
Copyright © 2011-2022 走看看