spring整合mybatis

本文详细介绍Spring框架如何整合MyBatis,包括所需jar包、数据源配置、事务管理及注解驱动等关键步骤,帮助读者掌握核心配置技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三、Spring整合MyBatis
spring包:spring-jdbc-x.x.x.jar、spring-tx-x.x.x.jar
spring整合mybatis:导包mybatis-spring-1.x.x.jar (MyBatis3.4+需要1.3+以上版本)
DataSource:
使用属性配置文件:占位符的方式(这里绝对不要多加空格)&lt;beanid=&quot;ppc&quot;class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;&gt;&lt;propertyname=&quot;locations&quot;value=&quot;classpath:jdbc.properties&quot;/&gt;&lt;/bean&gt;也可以配置:&lt;context:property−placeholderlocation=&quot;classpath:mysql.properties&quot;/&gt;如果不能识别{这里绝对不要多加空格}) &lt;bean id=&quot;ppc&quot; class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;&gt; &lt;property name=&quot;locations&quot; value=&quot;classpath:jdbc.properties&quot;/&gt; &lt;/bean&gt; 也可以配置: &lt;context:property-placeholder location=&quot;classpath:mysql.properties&quot;/&gt; 如果不能识别)<beanid="ppc"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="locations"value="classpath:jdbc.properties"/></bean><context:propertyplaceholderlocation="classpath:mysql.properties"/>{},不要配置default-autowire,或者修改属性ignore-unresolvable=“true”

或者使用扫描包下所有接口:

注意: 1、sqlSessionFactory可以不用注,自动将dao包下接口根据接口名第一个字母小写生成id名 2、如果使用了default-autowire="byName...",DataSource必须使用字符串常量 事务管理:默认catch到RuntimeException回滚:(对于手动处理的异常spring不再管理)

<tx:advice id=“txAdvice” transaction-manager=“tx”>
tx:attributes
<tx:method name=“exists” read-only=“true” />
<tx:method name=“add*” propagation=“REQUIRED”/>
<tx:method name="*" read-only=“true”
rollback-for=“DataAccessException”
no-rollback-for=“NullPointerException,ClassCastException” />
</tx:attributes>
</tx:advice>

aop:config
<aop:pointcut id=“bussinessService”
expression=“execution(public * com.cssl.service….(…))” />
<aop:advisor pointcut-ref=“bussinessService”
advice-ref=“txAdvice” />
</aop:config>

事务隔离级别:read-uncommited read-commited repeatable-read serializable
注意:
MyBatis没有事务默认每一条sql是一个事务!
readOnly:true|false 用于查询提高效率和防止意外插入、删除、更新操作
(MyBatis操作Oracle数据库时增删改也能提交,会自动修改其为false)
timeout :事务超时时间,有的数据库(MySQL)事务不支持

Propagation:
REQUIRED:业务方法需要在一个事务里运行。如果方法运行时,已经处在一个事务中,那么加入到这个事务,否则自己新建一个新的事务。

REQUIRES_NEW:不管是否存在事务,该方法总会为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务挂起(暂停),新的事务被创建。

NESTED:如果一个活动的事务存在,则运行在一个嵌套的事务中。它是已经存在事务的一个真正的子事务,如果没有活动事务,则按REQUIRED属性执行。它使用了一个单独的事务,这个事务拥有多个可以回滚的savepoint。内部事务的回滚不会对外部事务造成影响。
嵌套事务是外部事务的一部分, 只有外部事务结束后它才会被提交。

Annotation事务:
<tx:annotation-driven transaction-manager=“txManager”/>
类或方法前加@Trasactional
@Transactional(transactionManager=“txManager”,isolation=Isolation.READ_COMMITTED)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值