Original address: http://czj4451.iteye.com/blog/2037759
MyBatis and spring, transaction management more convenient, here is the way to use transactionnal, the wrong place, I hope you point out.
1. After integration with spring, use Spring's transaction management:
A. @Transactional method:
Create the Beans-da-tx.xml file under the Classpath and join the transaction configuration on the basis of Beans-da.xml (series five):
XML code
<!--Configure the transaction manager, note that the DataSource and Sqlsessionfactorybean datasource here are consistent, otherwise the transaction will not function--
<bean id= "TransactionManager"
class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name= "DataSource" ref= "DataSource"/>
</bean>
<tx:annotation-driven transaction-manager= "TransactionManager"/><!--transaction annotations driven, classes and methods labeled @transactional will have transactional -
Service class:
Java code
- @Service ("UserService")
- Public class UserService {
- @Autowired
- Iusermapper mapper;
- public int batchupdateuserswhenexception () { //non-transactional
- User user = new User (9, "before exception");
- int affectedcount = mapper.updateuser (user); //Successful execution
- User User2 = new User ("after exception");
- int i = 1/ 0; //Throw run-time exceptions
- int affectedCount2 = Mapper.updateuser (user2); //Not implemented
- if (Affectedcount = = 1 && affectedCount2 = = 1) {
- return 1;
- }
- return 0;
- }
- @Transactional
- public int txupdateuserswhenexception () { //transactional
- User user = new User (9, "before exception");
- int affectedcount = mapper.updateuser (user); //Rollback due to subsequent exception
- User User2 = new User ("after exception");
- int i = 1/ 0; //Throw run-time exception, transaction rollback
- int affectedCount2 = Mapper.updateuser (user2); //Not implemented
- if (Affectedcount = = 1 && affectedCount2 = = 1) {
- return 1;
- }
- return 0;
- }
- }
Mybatic transaction Management in conjunction with spring