从代码出发, 分析Java的事务管理发展
一、JDBC事务
Connection conn =
DataSourceUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
try {
Object retVal =
callback.doInConnection(conn);
conn.commit(); //提交事务
return retVal;
}catch (Exception e) {
conn.rollback();//回滚事务
throw e;
}finally {
conn.close();
}二、Hibernate事务
Session session = null;
Transaction transaction = null;
try {
session = factory.openSession();
//开启事务
transaction = session.beginTransaction();
transation.begin();
session.save(user);
transaction.commit();//提交事务
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();//回滚事务
return false;
}finally{
session.close();
}
三、Spring JDBC事务
[A]
public interface PlatformTransactionManager {
TransactionStatus getTransaction(TransactionDefinition definition)
throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
//1.获取事务管理器
PlatformTransactionManager txManager = (PlatformTransactionManager)
ctx.getBean("txManager");
//2.定义事务属性
DefaultTransactionDefinition td = new DefaultTransactionDefinition();
td.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
//3开启事务,得到事务状态
TransactionStatus status = txManager.getTransaction(td);
try {
//4.执行数据库操作
System.out.println(jdbcTempate.queryForInt("select count(*) from tbl_doc"));
//5、提交事务
txManager.commit(status);
}catch (Exception e) {
//6、回滚事务
txManager.rollback(status);
}
});
[B]
//1.获取事务管理器
PlatformTransactionManager txManager = (PlatformTransactionManager)
ctx.getBean("txManager");
//2、定义事务管理的模板
TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
//3.定义事务属性
transactionTemplate.
setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
//4.回调,执行真正的数据库操作,如果需要返回值需要在回调里返回
transactionTemplate.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
//5.执行数据库操作
System.out.println(jdbcTempate.queryForInt("select count(*) from tbl_doc"));
return null;
}
});
四、AOP
点赞
收藏
分享
文章举报
小卡雷尔
发布了1 篇原创文章 · 获赞 0 · 访问量 79
私信
关注