zoukankan      html  css  js  c++  java
  • Mybatis实现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.xml映射文件

             定义mapper映射文件UserMapper.xml(内容同Users.xml),需要修改namespace的值为 UserMapper接口路径。将UserMapper.xml放在classpath 下mapper目录 下。

    [html] view plain copy
     
     print?
    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="cn.itcast.mybatis.mapper.UserMapper">  
    6. <!-- 根据id获取用户信息 -->  
    7.     <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">  
    8.         select * from user where id = #{id}  
    9.     </select>  
    10. <!-- 自定义条件查询用户列表 -->  
    11.     <select id="findUserByUsername" parameterType="java.lang.String"   
    12.             resultType="cn.itcast.mybatis.po.User">  
    13.        select * from user where username like '%${value}%'   
    14.     </select>  
    15. <!-- 添加用户 -->  
    16.     <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">  
    17.     <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">  
    18.         select LAST_INSERT_ID()   
    19.     </selectKey>  
    20.       insert into user(username,birthday,sex,address)   
    21.       values(#{username},#{birthday},#{sex},#{address})  
    22.     </insert>  
    23.   
    24. </mapper>  

    三、Mapper.java(接口文件)

    [java] view plain copy
     
     print?
    1. /** 
    2.  * 用户管理mapper 
    3.  */  
    4. Public interface UserMapper {  
    5.     //根据用户id查询用户信息  
    6.     public User findUserById(int id) throws Exception;  
    7.     //查询用户列表  
    8.     public List<User> findUserByUsername(String username) throws Exception;  
    9.     //添加用户信息  
    10.     public void insertUser(User user)throws Exception;   
    11. }  


             接口定义有如下特点:
                      1、Mapper接口方法名和Mapper.xml中定义的statement的id相同
                      2、Mapper接口方法的输入参数类型和mapper.xml中定义的statement的parameterType的类型相同
                      3、Mapper接口方法的输出参数类型和mapper.xml中定义的statement的resultType的类型相同

    四、加载UserMapper.xml文件

             修改sqlMapConfig.xml文件:

    [html] view plain copy
     
     print?
    1. <!-- 加载映射文件 -->  
    2.  <mappers>  
    3.    <mapper resource="mapper/UserMapper.xml"/>  
    4.  </mappers>  

    五、测试

    [java] view plain copy
     
     print?
    1. Public class UserMapperTest extends TestCase {  
    2.   
    3.     private SqlSessionFactory sqlSessionFactory;  
    4.       
    5.     protected void setUp() throws Exception {  
    6.         //mybatis配置文件  
    7.         String resource = "sqlMapConfig.xml";  
    8.         InputStream inputStream = Resources.getResourceAsStream(resource);  
    9.         //使用SqlSessionFactoryBuilder创建sessionFactory  
    10.         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
    11.     }  
    12.   
    13.       
    14.     Public void testFindUserById() throws Exception {  
    15.         //获取session  
    16.         SqlSession session = sqlSessionFactory.openSession();  
    17.         //获取mapper接口的代理对象  
    18.         UserMapper userMapper = session.getMapper(UserMapper.class);  
    19.         //调用代理对象方法  
    20.         User user = userMapper.findUserById(1);  
    21.         System.out.println(user);  
    22.         //关闭session  
    23.         session.close();  
    24.           
    25.     }  
    26.     @Test  
    27.     public void testFindUserByUsername() throws Exception {  
    28.         SqlSession sqlSession = sqlSessionFactory.openSession();  
    29.         UserMapper userMapper = sqlSession.getMapper(UserMapper.class);  
    30.         List<User> list = userMapper.findUserByUsername("张");  
    31.         System.out.println(list.size());  
    32.   
    33.     }  
    34. Public void testInsertUser() throws Exception {  
    35.         //获取session  
    36.         SqlSession session = sqlSessionFactory.openSession();  
    37.         //获取mapper接口的代理对象  
    38.         UserMapper userMapper = session.getMapper(UserMapper.class);  
    39.         //要添加的数据  
    40.         User user = new User();  
    41.         user.setUsername("张三");  
    42.         user.setBirthday(new Date());  
    43.         user.setSex("1");  
    44.         user.setAddress("北京市");  
    45.         //通过mapper接口添加用户  
    46.         userMapper.insertUser(user);  
    47.         //提交  
    48.         session.commit();  
    49.         //关闭session  
    50.         session.close();  
    51.     }  
    52.       
    53.   
    54. }  

    六、总结

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


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

  • 相关阅读:
    找回密码
    找回密码,注册
    登陆
    返回与Table结构相同的DataTable副本
    同步表
    同步按照NewTable中ID存储情况将数据按照规则同步至OldTable,并清空OldTable中多余数据行,返回错误消息
    Page.IsPostBack
    GridView中点击某行的任意位置就选中该行
    c#后台计算2个日期之间的天数差
    分页存储过程,连接查询
  • 原文地址:https://www.cnblogs.com/efforts-will-be-lucky/p/7388791.html
Copyright © 2011-2022 走看看