mybatic與spring結(jié)合的事務(wù)管理
原文地址:http://czj4451.iteye.com/blog/2037759
mybatis與spring結(jié)合后,事務(wù)管理更加方便,這里介紹使用transactionnal的方式,有錯(cuò)的的地方,希望大家指出。
1. 和Spring集成后,使用Spring的事務(wù)管理:
a.?@Transactional方式:
在類路徑下創(chuàng)建beans-da-tx.xml文件,在applicationContext-resources.xml的基礎(chǔ)上加入事務(wù)配置:
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
服務(wù)類:
@Service("userService")
publicclass?UserService?{
@Autowired
IUserMapper?mapper;
publicint?batchUpdateUsersWhenException()?{//?非事務(wù)性
User?user?=new?User(9,"Before?exception");
int?affectedCount?=?mapper.updateUser(user);//?執(zhí)行成功
User?user2?=new?User(10,"After?exception");
int?i?=1?/0;//?拋出運(yùn)行時(shí)異常
int?affectedCount2?=?mapper.updateUser(user2);//?未執(zhí)行
if?(affectedCount?==1?&&?affectedCount2?==1)?{
return1;
}
return0;
}
@Transactional
publicint?txUpdateUsersWhenException()?{//?事務(wù)性
User?user?=new?User(9,"Before?exception");
int?affectedCount?=?mapper.updateUser(user);//?因后面的異常而回滾
User?user2?=new?User(10,"After?exception");
int?i?=1?/0;//?拋出運(yùn)行時(shí)異常,事務(wù)回滾
int?affectedCount2?=?mapper.updateUser(user2);//?未執(zhí)行
if?(affectedCount?==1?&&?affectedCount2?==1)?{
return1;
}
return0;
}
}