Mybatis-Spring基本知识

 Mybatis-Spring是将Mybatis和Spring进行融合的一个中间层插件,将Mybatis的一些工作交给Spring去做,主要包括SqlSessionFactory的创建、SqlSession的管理、事务管理以及异常的转化。这里需要注意一点就是Spring3.0支持iBatis2,但是不支持Mybatis3,因此才出现Mybatis-Spring,以后如果兼容了,可能也不会需要。

1、SqlSessionFactory的构造

(1)采用Spring的bean配置方式,利用SqlSessionFactoryBean来作为SqlSessionFactory的工厂,SqlSessionFactoryBean可以配置datasource(Spring的datasource都可以),配置文件,配置mapper xml的路径等,起到了SqlSessionFactoryBuilder的作用

(2)Mybatis-Spring的用法中,配置的SqlSessionFactory的bean通常作为属性传给SqlSessionDaoSupport的实现类或者SqlSessionTemplate,由它们去管理sqlSession

2、事务使用方式

只需配置Spring提供的事务管理bean,将配置给SqlSessionFactory的datasource配置给该事务管理bean即可

3、SqlSession的使用

最核心的类:SqlSessionTemplate是Mybatis-Spring的核心

(1)负责管理SqlSession,转换异常,是线程安全的,可以被多个DAO共享使用,保证SqlSession和当前的Spring事务相关,管理SqlSession的生命周期,包括关闭、提交和回滚。SqlSessionTemplate实现SqlSession接口,取代Mybatis默认的SqlSession实现DefaultSqlSession。SqlSessionTemplate可以通过SqlSessionFactory构造,SqlSessionDaoSupport的getSqlSession()返回SqlSessionTemplate,相当于也是通过SqlSessionTemplate实现。

(2)SqlSessionTemplate构造时,也可以传入ExecutorType作为参数,指定批量之类的。每个dao都是单例的,其中的sqlSession也就是唯一的,所以SqlSessionTemplate构建好之后,ExecutorType就指定了。

(3)SqlSessionTemplate拥有四个属性:sqlSessionFactory(构造sqlSession),executorType(定义执行类型),sqlSessionProxy(构造sqlSession的代理实现类),exceptionTranslator(将Mybatis的异常转化到Spring的DataAccessException异常)

(4)关键在于构造函数中SqlSessionTemplate会创建sqlSession的代理,其中配置了拦截器SqlSessionInterceptor做函数的调用拦截,主要完成sqlSession的获取、提交、关闭之类的操作,sqlSession的获取和事务有关

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章