三、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:
使用属性配置文件:占位符的方式(这里绝对不要多加空格)<beanid="ppc"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="locations"value="classpath:jdbc.properties"/></bean>也可以配置:<context:property−placeholderlocation="classpath:mysql.properties"/>如果不能识别{这里绝对不要多加空格})
<bean id="ppc" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties"/>
</bean>
也可以配置:
<context:property-placeholder location="classpath:mysql.properties"/>
如果不能识别这里绝对不要多加空格)<beanid="ppc"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="locations"value="classpath:jdbc.properties"/></bean>也可以配置:<context:property−placeholderlocation="classpath:mysql.properties"/>如果不能识别{},不要配置default-autowire,或者修改属性ignore-unresolvable=“true”
或者使用扫描包下所有接口:
<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)