MyBatis与Spring结合:

MyBatis与Spring结合,将MyBatis中的SqlSessionFactory、SqlSession交由Spring管理。

1.  SqlSessionFactoryBean

在MyBatis学习中讲到SqlSessionFactory是它的核心,使用SqlSessionFactoryBuilder来创建。而在MyBatis-Spring中,则使用 SqlSessionFactoryBean 来替代,Spring 将会在应用启动时为你 创建SqlSessionFactory 对象。

   MyBatis学习中讲到,从XML中构建SqlSessionFactory需要有四个重要配置:数据源,事务管理器,mapper,typeAliases。构建SqlSessionFactoryBuilder也同样需要这四个重要配置,将下面代码放置在在 Spring 的 XML 配置文件中:

   

 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.lili.test.model"></property>
<property name="mapperLocations" value="classpath*:com/lili/test/model/*Mapper.xml" />
</bean>

dataSource:数据源。

mapperLocations:对应mapper。指定 MyBatis 的XML 映射文件的位置。

typeAliasesPackage:对应typeAliases。指定Java对象的路径。

我们发现没有对应的事务管理器,在下一节写到。

2. 事务

MyBatis-Spring中的事务是利用了已经存在与Spring中的DataSourceTransactionManager,这样MyBatis 就参与到 Spring 的事务管理中。然后我们通常使用的AOP编程也是支持的。

要 开 启 Spring 的事 务 处 理 , 在 Spring 的 XML 配 置 文 件 中 简 单 创 建 一 个 DataSourceTransactionManager 对象:

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>

利用AOP编程:

<aop:config>
    <aop:pointcut id="pc" expression="execution(* com.lili.test.dao..*.*(..)) || execution(* com.lili.common.mybatis..*.*(..))" />
     <aop:advisor pointcut-ref="pc" advice-ref="txManager" order="1" />
</aop:config>

 

3. 使用SqlSessionTemplate实现数据库操作

在MyBatis中使用SqlSessionFactory创建SqlSession,在MyBatis-Spring中使用SqlSessionTemplate来负责管理 MyBatis 的 SqlSession。

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

  <constructor-arg index="0" ref="sqlSessionFactory" />

</bean>

这个bean可以直接注入到Dao中使用(baseDao中有一个sqlSessionTemplate属性):

<bean id="testBaseDao" abstract="true">

<property name="sqlSessionTemplate" ref="sqlSessionTemplate" />

</bean>

 





http://mybatis.github.io/spring/zh/sqlsession.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值