springmvc mybatis 手动提交事务

public void save(User user) {
//获取Spring容器的对象
WebApplicationContext contextLoader = ContextLoader.getCurrentWebApplicationContext();
//1.获取事务控制管理器
DataSourceTransactionManager transactionManager = contextLoader.getBean(
"txManager", DataSourceTransactionManager.class);
//2.获取事务定义
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//3.设置事务隔离级别,开启新事务
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
//4.获得事务状态
TransactionStatus status = transactionManager.getTransaction(def);
try {
//5.具体的数据库操作(多个)
User user1=new User();
user1.setUserName("今天");
user1.setAge("11");
mapper.save(user1);
//Integer.parseInt("dddddddd");
status.flush();
User user2=new User();
user2.setUserName("今天2");
user2.setAge("12");
mapper.save(user2);
} catch (Exception e) {
transactionManager.rollback(status);
}finally {     
transactionManager.commit(status);   

}

你可能感兴趣的:(springmvc mybatis 手动提交事务)