Mybatis第二弹

1      Dao开发方法

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

 

1.1    需求

将下边的功能实现Dao:

根据用户id查询一个用户信息

根据用户名称模糊查询用户信息列表

添加用户信息

 

1.2    SqlSession的使用范围

         SqlSession中封装了对数据库的操作,如:查询、插入、更新、删除等。

通过SqlSessionFactory创建SqlSession,而SqlSessionFactory是通过SqlSessionFactoryBuilder进行创建。

 

1.2.1  SqlSessionFactoryBuilder

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

 

1.2.2  SqlSessionFactory

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

 

1.2.3  SqlSession

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

 

执行过程如下:

1、  加载数据源等配置信息

Environment environment = configuration.getEnvironment();

2、  创建数据库链接

3、  创建事务对象

4、  创建Executor,SqlSession所有操作都是通过Executor完成,mybatis源码如下:

 

if(ExecutorType.BATCH == executorType) {

      executor = newBatchExecutor(this, transaction);

    } elseif (ExecutorType.REUSE == executorType) {

      executor = new ReuseExecutor(this, transaction);

    } else {

      executor = new SimpleExecutor(this, transaction);

    }

if (cacheEnabled) {

      executor = new CachingExecutor(executor,autoCommit);

    }

 

5、  SqlSession的实现类即DefaultSqlSession,此对象中对操作数据库实质上用的是Executor

 

结论:

         每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能共享使用,它也是线程不安全的。因此最佳的范围是请求或方法范围。绝对不能将SqlSession实例的引用放在一个类的静态字段或实例字段中。

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

         SqlSession session = sqlSessionFactory.openSession();

         try {

                  // do work

         } finally {

                session.close();

         }

 

 

1.3    原始Dao开发方式

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

1.3.1  映射文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTDMapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="test">

<!-- 根据id获取用户信息 -->

    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">

       select * fromuser where id = #{id}

    </select>

<!-- 添加用户 -->

    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">

    <selectKey keyProperty="id" order="AFTER"resultType="java.lang.Integer">

       selectLAST_INSERT_ID()

    </selectKey>

      insert into user(username,birthday,sex,address)

      values(#{username},#{birthday},#{sex},#{address})

    </insert>

</mapper>

 

 

1.3.2  Dao接口

Public interface UserDao {

    public User getUserById(int id) throws Exception;

    public void insertUser(User user) throws Exception;

}

 

Public class UserDaoImpl implements UserDao {

   

    //注入SqlSessionFactory

    public UserDaoImpl(SqlSessionFactorysqlSessionFactory){

       this.setSqlSessionFactory(sqlSessionFactory);

    }

   

    private SqlSessionFactory sqlSessionFactory;

    @Override

    public User getUserById(int id) throws Exception {

       SqlSession session = sqlSessionFactory.openSession();

       User user = null;

       try {

           //通过sqlsession调用selectOne方法获取一条结果集

           //参数1:指定定义的statementid,参数2:指定向statement中传递的参数

           user = session.selectOne("test.findUserById", 1);

           System.out.println(user);

                    

       } finally{

           session.close();

       }

       return user;

    }

   

    @Override

    Public void insertUser(User user) throws Exception {

       SqlSession sqlSession =sqlSessionFactory.openSession();

       try {

           sqlSession.insert("insertUser", user);

           sqlSession.commit();

       } finally{

           session.close();

       }

      

    }

}

 

1.3.3  问题

原始Dao开发中存在以下问题:

u  Dao方法体存在重复代码:通过SqlSessionFactory创建SqlSession,调用SqlSession的数据库操作方法

u  调用sqlSession的数据库操作方法需要指定statementid,这里存在硬编码,不得于开发维护。

 

1.4    Mapper动态代理方式

1.4.1  实现原理

         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.4.2 Mapper.xml(映射文件)

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

 

<?xml version="1.0"encoding="UTF-8" ?>

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTDMapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mappernamespace="cn.itcast.mybatis.mapper.UserMapper">

<!-- 根据id获取用户信息 -->

    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">

       select * from user where id =#{id}

    </select>

<!-- 自定义条件查询用户列表 -->

    <select id="findUserByUsername"parameterType="java.lang.String"

           resultType="cn.itcast.mybatis.po.User">

      select * from user where username like '%${value}%'

    </select>

<!-- 添加用户 -->

    <insert id="insertUser"parameterType="cn.itcast.mybatis.po.User">

    <selectKey keyProperty="id"order="AFTER" resultType="java.lang.Integer">

       select LAST_INSERT_ID()

    </selectKey>

     insert into user(username,birthday,sex,address)

     values(#{username},#{birthday},#{sex},#{address})

    </insert>

 

</mapper>

 

1.4.3 Mapper.java(接口文件)

 

/**

 * 用户管理mapper

 */

Public interface UserMapper {

    //根据用户id查询用户信息

    public User findUserById(int id) throws Exception;

    //查询用户列表

    public List<User>findUserByUsername(String username) throws Exception;

    //添加用户信息

    publicvoid insertUser(User user)throws Exception;

}

 

接口定义有如下特点:

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

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

3、  Mapper接口方法的输出参数类型和mapper.xml中定义的statement的resultType的类型相同

 

1.4.4  加载UserMapper.xml文件

修改SqlMapConfig.xml文件:

 

  <!-- 加载映射文件 -->

  <mappers>

    <mapper resource="mapper/UserMapper.xml"/>

  </mappers>

 

 

1.4.5  测试

 

Public class UserMapperTest extends TestCase {

 

    private SqlSessionFactory sqlSessionFactory;

   

    protected void setUp() throws Exception {

       //mybatis配置文件

       String resource = "sqlMapConfig.xml";

       InputStream inputStream =Resources.getResourceAsStream(resource);

       //使用SqlSessionFactoryBuilder创建sessionFactory

       sqlSessionFactory = newSqlSessionFactoryBuilder().build(inputStream);

    }

 

   

    Public void testFindUserById() throws Exception {

       //获取session

       SqlSession session = sqlSessionFactory.openSession();

       //获取mapper接口的代理对象

       UserMapper userMapper =session.getMapper(UserMapper.class);

       //调用代理对象方法

       User user = userMapper.findUserById(1);

       System.out.println(user);

       //关闭session

       session.close();

      

    }

    @Test

    publicvoid testFindUserByUsername() throws Exception {

       SqlSession sqlSession = sqlSessionFactory.openSession();

       UserMapper userMapper =sqlSession.getMapper(UserMapper.class);

       List<User> list =userMapper.findUserByUsername("");

       System.out.println(list.size());

 

    }

Public void testInsertUser() throws Exception {

       //获取session

       SqlSession session = sqlSessionFactory.openSession();

       //获取mapper接口的代理对象

       UserMapper userMapper =session.getMapper(UserMapper.class);

       //要添加的数据

       User user = new User();

       user.setUsername("张三");

       user.setBirthday(new Date());

       user.setSex("1");

       user.setAddress("北京市");

       //通过mapper接口添加用户

       userMapper.insertUser(user);

       //提交

       session.commit();

       //关闭session

       session.close();

    }

   

 

}

 

1.4.6  总结

u  selectOne和selectList

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

 

u  namespace

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值