前些天同事要使用spring 事务管理,按照我给的方法使用的时候,一直不生效。
然后我就慌了,辛苦总结的东西给别人居然不能用。
网上找了很多原因。
1.spring 注入同一个实例在contro层 的扫描包里,也住service 的扫描包里,注入两次,导致事务不生效、排除
2.spring 中使用AOP 注解的事务管理机制,注解一定要在PUBLIC方法上。 查看代码确实是这个问题。
代码结构是,service 实现类,实现类里面有自己定义的一个私有方法,在私有方法上使用事务注解功能。
将这个私有方法改为public . 结果还是不行。
/**
* 添加人员领取记录,修改活动剩余金额
*
* @param userID
* 人员ID
* @param actEntity
* 要参与的活动
* @return
* @throws SQLClientInfoException
* @throws Exception
*/
@Transactional("qxTransaction")
public boolean saveLog(String userID, String phone, ActivityGH actEntity,String money) {
ActivityGHList entity = new ActivityGHList();
entity.setUserID(userID);
entity.setActCode(actEntity.getActCode());
entity.setPhone(phone);
entity.setSourceCode(actEntity.getSourceCode());
entity.setMoney(money);
entity.setYearMonth(RDate.format(new Date(), "yyyyMM"));
/** 使用BigDecimal 进行金额的计算 */
BigDecimal lastMoney = parse(actEntity.getCostMoney()).add(parse(money));
actEntity.setCostMoney(lastMoney.toString());
_logger.info("发放金额 : "+money+",剩余金额:"+lastMoney);
/** 领取数量+1 */
if (actEntity.getSpendNumber() == null) {
actEntity.setSpendNumber(1);
} else {
actEntity.setSpendNumber(actEntity.getSpendNumber() + 1);
}
RResult result = actService.updateCostMoney(actEntity);
if ("S".equals(result.getCode())) {
Integer t = actListService.save(entity);
return t > 0;
}
return false;
}
这就很尴尬了。看以前的代码使用。发现了一个不同点。
以前在使用注解事务的时候,都是在service 的 覆盖方法上,
@Override
@Transactional("qxTransaction")
public Long test(BsCoach bsCoach) throws Exception {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test1");
//1修改教练操作
bsCoachDao.update(bsCoach1);
//2修改学员操作,异常
try {
BsStudent bsStudent = new BsStudent();
bsStudentDao.update(bsStudent);
} catch (Exception e) {
throw e;
}
return bsCoach1.getCid();
}
然后我将 注解加到service 接口覆盖方法上。再试。然后真的成功了。
结果表明,spring AOP 事务注解方法,如果加在service 实现类上,需要加在覆盖方法上,AOP才能拦截到。
项目里面一直使用的是SpringMVC。 对于事务处理使用的spring 自带的事务管理机制。
就如何使用大概说说明一下:
为了自己以后能看的懂,还是说的详细一些
1,web.xml(启动都是从这里开始的)
<!-- 定义Spring的配置的位置,可以定义多个配置文件,可以使用通配符 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/env/applicationContext.xml</param-value>
</context-param>
2.看applicationContext.xml 这个配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<!-- 数据库设置 -->
<import resource="classpath:config/spring/spring-data-config.xml" />
<!-- 服务层设置 -->
<import resource="classpath:config/spring/spring-service-config.xml" />
</beans>
3 看spring-data-config.xml 这个数据库配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"
default-lazy-init="true">
<!--上面的这些引用 真的不能少-->
<!-- import properties file 加载数据库的一些配置文件 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/env/dataSource.properties</value>
<value>classpath:config/env/mongoDbSource.properties</value>
</list>
</property>
</bean>
<!-- ****************************** mongoDB begin ********************************** -->
<!-- nosql数据库的 配置一些连接属性的设置 -->
<mongo:mongo id="mongo" replica-set="${mongo.dburl}">
<mongo:options connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
auto-connect-retry="${mongo.autoConnectRetry}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
slave-ok="${mongo.slaveOk}"
write-number="1"
write-timeout="0"
write-fsync="true" />
</mongo:mongo>
<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
<mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongo" />
<bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<!-- 去除集合里的_class属性 -->
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey">
<null />
</constructor-arg>
</bean>
<bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>
<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
</bean>
<!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
<mongo:mapping-converter base-package="com.qx.mongodb.doc" />
<!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
<mongo:repositories base-package="com.qx.mongodb.dao" />
<!-- ***************************** mongoDB over ********************************** -->
<!-- ************* 这里才是我想要说的地方qx config begin********************************** -->
<!-- 1,引入数据库配置,使用的驱动jolbox -->
<bean id="qxDataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<property name="driverClass" value="${qx.driverClass}" />
<property name="jdbcUrl" value="${qx.jdbcUrl}" />
<property name="username" value="${qx.username}" />
<property name="password" value="${qx.password}" />
<property name="idleConnectionTestPeriod" value="${pool.idleConnectionTestPeriod}" />
<property name="idleMaxAge" value="${pool.idleMaxAge}" />
<property name="maxConnectionsPerPartition" value="${pool.maxConnectionsPerPartition}" />
<property name="minConnectionsPerPartition" value="${pool.minConnectionsPerPartition}" />
<property name="partitionCount" value="${pool.partitionCount}" />
<property name="acquireIncrement" value="${pool.acquireIncrement}" />
<property name="statementsCacheSize" value="${pool.statementsCacheSize}" />
<property name="releaseHelperThreads" value="${pool.releaseHelperThreads}" />
</bean>
<!-- 2,mybaties的sqlsession工厂bean -->
<bean id="qxSqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="qxDataSource" />
<property name="mapperLocations" value="classpath*:config/sqlmap/qxuser/**/*.xml" />
</bean>
<!-- 2,定义改数据库的事务-->
<bean id="qxTransaction"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="qxDataSource" />
</bean>
<!-- 3,引入注解方式的驱动,这样可以在代码中使用注解的方式使用事务-->
<tx:annotation-driven transaction-manager="qxTransaction" />
<!-- *************qx config end******************************************** -->
<!-- 下面的是另外的一个数据库的配置,同上->
<!-- *************qx_platform config begin****************************************** -->
<bean id="dataSourceMySql" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<property name="driverClass" value="${qx_platform.driverClass}" />
<property name="jdbcUrl" value="${qx_platform.jdbcUrl}" />
<property name="username" value="${qx_platform.username}" />
<property name="password" value="${qx_platform.password}" />
<property name="idleConnectionTestPeriod" value="${pool.idleConnectionTestPeriod}" />
<property name="idleMaxAge" value="${pool.idleMaxAge}" />
<property name="maxConnectionsPerPartition" value="${pool.maxConnectionsPerPartition}" />
<property name="minConnectionsPerPartition" value="${pool.minConnectionsPerPartition}" />
<property name="partitionCount" value="${pool.partitionCount}" />
<property name="acquireIncrement" value="${pool.acquireIncrement}" />
<property name="statementsCacheSize" value="${pool.statementsCacheSize}" />
<property name="releaseHelperThreads" value="${pool.releaseHelperThreads}" />
</bean>
<bean id="sqlSessionFactoryMysql" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceMySql" />
<property name="mapperLocations" value="classpath*:config/sqlmap/mysql/**/*.xml" />
</bean>
<bean id="transactionManagerMysql" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceMySql" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerMysql" />
<!-- *************qx_platform config end****************************************** -->
<!--这是配置使用分布式事务,因为如果使用的不是同一个数据源,则需要使用这样的跨数据源的事务-->
<!-- *************jta config begin****************************************** -->
<bean id="jtaTransaction" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<bean class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
<property name="forceShutdown" value="true" />
</bean>
</property>
<property name="userTransaction">
<bean class="com.atomikos.icatch.jta.UserTransactionImp" />
</property>
</bean>
<!-- *************jta config end****************************************** -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<aop:config>
<aop:pointcut id="tracePointcut"
expression="target(com.tom.util.spring.ISpringObject)" />
</aop:config>
<bean id="daoIntroductionInterceptor" class="com.tom.util.data.FBatisDaoIntroductionInterceptor" />
<!-- 配置DAO层切入点 -->
<bean id="audienceAdvisor"
class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
<property name="advice" ref="daoIntroductionInterceptor" />
<property name="expression" value="execution(* com..*.dao..*Dao.*(..))" />
</bean>
<!-- 切面 -->
<bean id="abstractDao" class="org.springframework.aop.framework.ProxyFactoryBean"
abstract="true">
<property name="interceptorNames">
<list>
<value>audienceAdvisor</value>
</list>
</property>
</bean>
<bean id="abstractQxDaoTarget" class="com.tom.util.data.mybatis.FAbstractMybatisDaoImpl"
abstract="true">
<property name="sqlSessionFactory" ref="qxSqlSession" />
</bean>
<bean id="abstractQxOrderDaoTarget" class="com.tom.util.data.mybatis.FAbstractMybatisDaoImpl"
abstract="true">
<property name="sqlSessionFactory" ref="qxOrderSqlSession" />
</bean>
<import resource="classpath:config/spring/mysql-user-dao-config.xml" />
<import resource="classpath:config/spring/mysql-system-dao-config.xml" />
<import resource="classpath:config/spring/user-coach-dao-config.xml" />
<import resource="classpath:config/spring/user-bs-dao-config.xml" />
<import resource="classpath:config/spring/user-cm-dao-config.xml" />
<import resource="classpath:config/spring/business-dao-config.xml" />
<import resource="classpath:config/spring/order-dao-config.xml" />
</beans>
4 使用方式。
这里补充说明一下:如果指定的事务和实际操作的数据,不一致,是不会回滚的。
我自己写了一个简单的例子。
第一种情况,同源数据
@Override
@Transactional("qxTransaction")
public Long test(BsCoach bsCoach) {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test1");
//1修改教练操作
bsCoachDao.update(bsCoach1);
//2修改学员操作,异常
BsStudent bsStudent = new BsStudent();
bsStudentDao.update(bsStudent);
return bsCoach1.getCid();
}
这样在第2步操作后,操作异常,查看结果就会发现,第一步没有被提交。事务回滚了。
第二种 同源数据,异常被try catch
如果代码是这样的,出错的操作被Try catch了。
@Override
@Transactional("qxTransaction")
public Long test(BsCoach bsCoach) {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test1");
//1修改教练操作
bsCoachDao.update(bsCoach1);
//2修改学员操作,异常
try {
BsStudent bsStudent = new BsStudent();
bsStudentDao.update(bsStudent);
} catch (Exception e) {
// TODO: handle exception
}
return bsCoach1.getCid();
}
查看结果发现,第一步还是执行成功了。虽然第二部出错,但是try catch 了,所以异常不会回滚.
第三种 同源数据,异常被抛出
再次但是如果,我在异常里面捕获异常,但是会抛出,或者说是主动抛出异常,结果呢?
@Override
@Transactional("qxTransaction")
public Long test(BsCoach bsCoach) throws Exception {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test1");
//1修改教练操作
bsCoachDao.update(bsCoach1);
//2修改学员操作,异常
try {
BsStudent bsStudent = new BsStudent();
bsStudentDao.update(bsStudent);
} catch (Exception e) {
throw e;
}
return bsCoach1.getCid();
}
查看结果知道:第一步操作没有成功,说明事务回滚了。
得出:抛出异常,也是可以回滚事务的。
第四种 同源数据,异常被抛出
分布式事务
事务的标签使用之前定义的分布式事务。
@Override
@Transactional("jtaTransaction")
public Long test3(BsCoach bsCoach) {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test3");
// 数据源1 的操作
bsCoachDao.update(bsCoach1);
BsOrderCancel bsOrderCancel = new BsOrderCancel();
//数据源2 的操作
bsOrderCancelService.update(bsOrderCancel);
return bsCoach1.getCid();
}
第五种 同源数据,指定异常回滚
看代码如下
@Override
@Transactional(rollbackFor=Exception.class,value="qxTransaction")
public Long test(BsCoach bsCoach) throws FRequestException {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test1");
bsCoachDao.update(bsCoach1);
try {
BsStudent bsStudent = new BsStudent();
bsStudentDao.update(bsStudent);
} catch (Exception e) {
throw new FRequestException(1, "2222");
}
return bsCoach1.getCid();
}
这是事务的第二种写法,可以指定异常回滚,默认都是 Excepiton的异常。
我抛出的异常是:FRequestException 。
因为FRequestException 继承自Exception ,所以结果也是回滚了。
但是如果指定的异常和抛出的异常不一致呢
@Override
@Transactional(rollbackFor=NullPointerException.class,value="qxTransaction")
public Long test(BsCoach bsCoach) throws FRequestException {
BsCoach bsCoach1 = new BsCoach();
bsCoach1.setCid(1100033L);
bsCoach1 = bsCoachDao.load(bsCoach1);
bsCoach1.setFullName("test1");
bsCoachDao.update(bsCoach1);
try {
BsStudent bsStudent = new BsStudent();
bsStudentDao.update(bsStudent);
} catch (Exception e) {
throw new FRequestException(1, "2222");
}
return bsCoach1.getCid();
}
看到结果发现,事务没有回滚。
因为这里指定的回滚异常是:NullPointerException
而我抛出的异常是:FRequestException。
这就是指定异常回滚。
这里补充说明一下事物指定异常回滚的机制
默认情况下,springMVC 事物回滚的异常只有 RuntimeException 运行时异常
RuntimeException是继承于Exception ,所以不是所有的异常都会事物回滚。
如果你自己定义一个自定义的异常类型是继承于 Exception ,但是在事物配置的时候,没有指定该异常回滚,那是不会回滚的。
如果想要自定义的异常 抛出能回滚,第一种就是继承RuntimeException 第二种就是指定改异常回滚