分享

MyBatis学习

 Baruch 2017-09-10
  • 简介

  使用Mybatis开发Dao,通常有两个方法,即原始Dao开发方法和Mapper接口开发方法。

  • 主要概念介绍:

  MyBatis中进行Dao开发时候有几个重要的类,它们是SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession。

  SqlSession中封装了对数据库的操作,如:查询、插入、更新、删除等。通过SqlSessionFactory创建SqlSession,而SqlSessionFactory是通过SqlSessionFactoryBuilder进行创建。

  1、SqlSessionFactoryBuilder

  SqlSessionFactoryBuilder用于创建SqlSessionFacoty,SqlSessionFacoty一旦创建完成就不需要SqlSessionFactoryBuilder了,因为SqlSession是通过SqlSessionFactory生产,所以可以将SqlSessionFactoryBuilder当成一个工具类使用,最佳使用范围是方法范围即方法体内局部变量。

  2、SqlSessionFactory

  SqlSessionFactory是一个接口,接口中定义了openSession的不同重载方法,SqlSessionFactory的最佳使用范围是整个应用运行期间,一旦创建后可以重复使用,通常以单例模式管理SqlSessionFactory

  3、SqlSession

  SqlSession是一个面向用户的接口, sqlSession中定义了数据库操作,默认使用DefaultSqlSession实现类。

  SqlSession中提供了很多操作数据库的方法:如:selectOne(返回单个对象)selectList(返回单个或多个对象),SqlSession是线程不安全的,在SqlSesion实现类中除了有接口中的方法(操作数据库的方法)还有数据域属性,SqlSession最佳应用场合在方法体内,定义成局部变量使用,绝对不能将SqlSession实例的引用放在一个类的静态字段或实例字段中。

  打开一个 SqlSession;使用完毕就要关闭它。通常把这个关闭操作放到 finally 块中以确保每次都能执行关闭。如下:

 

复制代码
1 SqlSession session = sqlSessionFactory.openSession();
2 try {
3       // do work
4 } finally {
5       session.close();
6 }
复制代码

 

  • 原始Dao开发方式

  原始Dao开发方法需要程序员编写Dao接口和Dao实现类。

  还是以前文提到的简单的增删改查为例,来简单介绍原始Dao开发方式。

  1、映射文件

 

复制代码
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-////DTD Mapper 3.0//EN"
 4 "http:///dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="user">
 6     <!-- 根据id获取用户信息 -->
 7     <select id="findUserById" parameterType="int" resultType="user">
 8         select * from user where id = #{id}
 9     </select>
10     <!-- 根据username模糊查询用户信息 -->
11     <select id="findUserByName" parameterType="java.lang.String" resultType="com.luchao.mybatis.first.po.User">
12         select * from user where username like '%${value}%'
13     </select>
14     <!-- 添加用户信息 -->
15     <insert id="insertUser" parameterType="com.luchao.mybatis.first.po.User">
16         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
17             select LAST_INSERT_ID()
18         </selectKey>
19         insert into user(username,birthday,sex,address) value (#{username},#{birthday},#{sex},#{address});
20     </insert>
21     <!-- 根据id删除用户信息 -->
22     <delete id="deleteUser" parameterType="int">
23         delete from user where id=#{id}
24     </delete>
25     <!-- 修改用户信息 -->
26     <update id="updateUser" parameterType="com.luchao.mybatis.first.po.User">
27         update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
28         where id=#{id}
29     </update>
30 </mapper>
复制代码

 

  2、Dao接口

复制代码
1 public interface UserDao {
2     //根据ID查询用户信息
3     public User findUserById(int id) throws Exception;
4     //添加用户信息
5     public void insertUser(User user) throws Exception;
6     //删除用户信息
7     public void deleteUser(int id) throws Exception;
8 }
复制代码

  3、Dao接口实现类

复制代码
 1 public class UserDaoImpl implements UserDao{
 2     
 3     // 需要向dao实现类中注入SqlSessionFactory
 4     // 这里通过构造方法注入
 5     private SqlSessionFactory sqlSessionFactory;
 6     
 7     public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
 8         super();
 9         this.sqlSessionFactory = sqlSessionFactory;
10     }
11     @Override
12     public void deleteUser(int id) throws Exception {
13         SqlSession sqlSession = sqlSessionFactory.openSession();
14         //执行删除操作
15         sqlSession.insert("user.deleteUser", id);
16         // 提交事务
17         sqlSession.commit();
18         // 释放资源
19         sqlSession.close();
20     }
21     @Override
22     public User findUserById(int id) throws Exception {
23         SqlSession sqlSession = sqlSessionFactory.openSession();//获取sqlSession
24         User user = sqlSession.selectOne("user.findUserById", id);
25         sqlSession.close();//关闭资源
26         return user;
27     }
28     @Override
29     public void insertUser(User user) throws Exception {
30         SqlSession sqlSession = sqlSessionFactory.openSession();
31         //执行插入操作
32         sqlSession.insert("user.insertUser", user);
33         // 提交事务
34         sqlSession.commit();
35         // 释放资源
36         sqlSession.close();
37     }
38 }
复制代码

  4、测试代码:

复制代码
 1 public class MyBatis_dao_test {
 2     private SqlSessionFactory sqlSessionFactory;
 3     @Before
 4     public void init() throws IOException{
 5         //创建sqlSessionFactory
 6         //MyBatis配置文件
 7         String resource = "SqlMapConfig.xml";
 8         //得到配置文件流
 9         InputStream inputStream = Resources.getResourceAsStream(resource);
10         //创建会话工厂,传入MyBatis的配置信息
11         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
12     }
13     @Test
14     public void testFindUserById() throws Exception{
15         //创建UserDao对象
16         UserDao userDao = new UserDaoImpl(sqlSessionFactory);
17         //调用UserDao的方法,根据ID查找user
18         User user = userDao.findUserById(10);
19         //打印客户信息
20         System.out.println(user);
21     }
22 }
复制代码

  5、原始Dao方法总结:

  (1)、dao接口实现类方法中存在大量模板方法,如:通过SqlSessionFactory创建SqlSession,调用SqlSession的数据库操作方法。

  (2)、调用sqlSession的数据库操作方法需要指定statementid,这里存在硬编码。

  (3)、调用sqlsession方法时传入的变量,由于sqlsession方法使用泛型,即使变量类型传入错误,在编译阶段也不报错,不利于程序员开发。

  • Mapper动态代理方式

  1、实现原理

  Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。这样通过动态代理就实现了将模板方法进行封装,只需要实现具体的实现即可。

 

  Mapper接口开发需要遵循以下规范:

 

  (1)、 Mapper.xml文件中的namespacemapper接口的类路径相同。

 

  (2)、 Mapper接口方法名和Mapper.xml中定义的每个statementid相同 。

 

  (3)、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql parameterType的类型相同。

 

  (4)、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sqlresultType的类型相同。

  2、Mapper.xml(映射文件)

  映射文件与原始Dao开发的映射文件相似,只需要将namespace定于为mapper接口全路径。

 

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-////DTD Mapper 3.0//EN"
"http:///dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.luchao.mybatis.first.mapper.UserMapper">
    <!-- 根据id获取用户信息 -->
    <select id="findUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>
    <!-- 根据username模糊查询用户信息 -->
    <select id="findUserByName" parameterType="java.lang.String" resultType="com.luchao.mybatis.first.po.User">
        select * from user where username like '%${value}%'
    </select>
    <!-- 添加用户信息 -->
    <insert id="insertUser" parameterType="com.luchao.mybatis.first.po.User">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into user(username,birthday,sex,address) value (#{username},#{birthday},#{sex},#{address});
    </insert>
    <!-- 根据id删除用户信息 -->
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
    <!-- 修改用户信息 -->
    <update id="updateUser" parameterType="com.luchao.mybatis.first.po.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
        where id=#{id}
    </update>
</mapper>
复制代码

 

  3、Mapper.java(接口文件)

 

复制代码
 1 public interface UserMapper {
 2     //根据ID查询用户信息
 3     public User findUserById(int id) throws Exception;
 4     //添加用户信息
 5     public void insertUser(User user) throws Exception;
 6     //删除用户信息
 7     public void deleteUser(int id) throws Exception;
 8     //更新用户信息
 9     public void updateUser(User user) throws Exception;
10     //根据用户名模糊查找
11     public List<User> findUserByName(String user) throws Exception;
12 }
复制代码

 

  接口定义有如下特点:

  (1)、 Mapper接口方法名和Mapper.xml中定义的statement的id相同。

  (2)、 Mapper接口方法的输入参数类型和mapper.xml中定义的statement的parameterType的类型相同。

  (3)、 Mapper接口方法的输出参数类型和mapper.xml中定义的statementresultType的类型相同。

  4、加载UserMapper.xml文件

  在SqlMapConfig.xml文件中加载UserMapper.xml,如下:

1 <mappers>
2     <mapper resource="mapper/UserMapper.xml"/>
3 </mappers>

  5、测试代码:

复制代码
 1 public class MyBatis_mapper_test {
 2     private SqlSessionFactory sqlSessionFactory;
 3     @Before
 4     public void init() throws IOException{
 5         //创建sqlSessionFactory
 6         //MyBatis配置文件
 7         String resource = "SqlMapConfig.xml";
 8         //得到配置文件流
 9         InputStream inputStream = Resources.getResourceAsStream(resource);
10         //创建会话工厂,传入MyBatis的配置信息
11         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
12     }
13     @Test
14     public void testFindUserById() throws Exception{
15         //获取sqlSession对象
16         SqlSession sqlSession = sqlSessionFactory.openSession();
17         //创建UserMapper对象,MyBatis自动生成mapper代理
18         UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
19         //调用userMapper的方法
20         User user = userMapper.findUserById(10);
21         //关闭资源
22         sqlSession.close();
23         //打印客户信息
24         System.out.println(user);
25     }
26 }
复制代码

  5、Mapper动态代理总结:

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

  (2)、使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。在系统中,dao层的代码是被业务层公用的。即使mapper接口只有一个参数,可以使用包装类型的pojo满足不同的业务方法的需求。

 

   注意:持久层方法的参数可以包装类型、map等,service方法中建议不要使用包装类型(不利于业务层的可扩展)。

  mybatis开发dao的方法有两种:原始Dao开发和Mapper动态代理开发,这两种各有优点。原始Dao开发:程序员要写Dao和Dao实现,需要些较多的代码,但是比较好理解。Mapper动态代理:程序员只需要写Mapper接口,然后按照规范进行配置,MyBatis就会自动实现类似Dao实现,减少模板方法。mybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。

 

 

 

 

 

 

 

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多