spring整合mybatis是如何配置事務的?
http://czj4451.iteye.com/blog/2037759
mybatis的事務管理:
一、單獨使用mybatis組件,使用SqlSession來處理事務:public class MyBatisTxTest {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} finally {
if (reader != null) {
reader.close();
}
}
}
@Test
public void updateUserTxTest() {
SqlSession session = sqlSessionFactory.openSession(false); // 打開會話,事務開始
try {
IUserMapper mapper = session.getMapper(IUserMapper.class);
User user = new User(9, "Test transaction");
int affectedCount = mapper.updateUser(user); // 因後面的異常而未執行commit語句
User user = new User(10, "Test transaction continuously");
int affectedCount2 = mapper.updateUser(user2); // 因後面的異常而未執行commit語句
int i = 2 / 0; // 觸發運行時異常
session.commit(); // 提交會話,即事務提交
} finally {
session.close(); // 關閉會話,釋放資源
}
}
}
測試會發現數據沒有被修改
和Spring集成後,使用Spring的事務管理: &
&
&
&
&
&
&
&
&
&
&
&
&
&
&
&
&
&
&
&
&
& @Autowired public int batchUpdateUsersWhenException() { // 非事務性 @Transactional @Resource @Test @Test
@Service("userService")
public class UserService {
IUserMapper mapper;
User user = new User(9, "Before exception");
int affectedCount = mapper.updateUser(user); // 執行成功
User user2 = new User(10, "After exception");
int i = 1 / 0; // 拋出運行時異常
int affectedCount2 = mapper.updateUser(user2); // 未執行
if (affectedCount == 1 affectedCount2 == 1) {
return 1;
}
return 0;
}
public int txUpdateUsersWhenException() { // 事務性
User user = new User(9, "Before exception");
int affectedCount = mapper.updateUser(user); // 因後面的異常而回滾
User user2 = new User(10, "After exception");
int i = 1 / 0; // 拋出運行時異常,事務回滾
int affectedCount2 = mapper.updateUser(user2); // 未執行
if (affectedCount == 1 affectedCount2 == 1) {
return 1;
}
return 0;
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:beans-da-tx.xml" })
public class SpringIntegrateTxTest {
UserService userService;
public void updateUsersExceptionTest() {
userService.batchUpdateUsersWhenException();
}
public void txUpdateUsersExceptionTest() {
userService.txUpdateUsersWhenException();
}
}
&
&
&
@Transactional
public void blabla(){
}
兩種方式,一種是利用註解,另一種是spring的aop,詳細的回復我再說吧
推薦閱讀:
※【spring指南系列】計劃任務
※【spring指南系列】使用Redis進行消息傳遞
※快速了解spring事務七種傳播方式、事務的4種隔離級別、臟讀、重複讀、幻讀;
TAG:Spring |