数据库事务的定义
事务是指一组相互信赖的操作行为。这些操作要么必须全部成功,要么必须全部失败,以保证数据的一致性和完整性。
数据库事务是对现实生活中事务的模拟,它由一组在业务逻辑上相互信赖的SQL语句组成。
数据库事务的ACID属性
原子性(Atomic)
指整个数据库事务是不可分割的工作单元。原子性确保在事务中的所有操作要么都发生,要么都不发生。
一致性(Consistency)
一旦一个事务结束了(不管成功与否),系统所处的状态和它的业务规则是一致的。即数据应当不会被破坏。
隔离性(Isolation)
指多个事务同时操作同一数据时,每个事务都有各自的完整数据空间。
持久性(Durability)
一旦事务完成,事务的结果应该持久化。
JDBC声明事务
Connection con = null;
PreparedStatement pstmt = null;
try{
con = DriverManager.getConnection(dbUrl, username, password);
//设置手工提交事务模式
con.setAutoCommit(false);
pstmt = ……;
pstmt.executeUpdate();
//提交事务
con.commit();
}catch(Exception e){
//事务回滚
con.rollback();
…..
} finally{
…….
}
Hibernate 事务
1、如果Hibernat持久层运行在一个非托管环境中,可以在hibernate配置文件 hibernate.cfg.xml中指定:
<session-factory> <property name="transaction.factory_class"> org.hibernate.transaction.JDBCTransactionFactory </property> </session-factory>
Transaction tx = null;
try {
tx = session.beginTransaction();
// do some work...
tx.commit();
}catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}finally {
session.close();
}
注:
-
不管事务成功与否,最后都应该调用Session的close()方法来关闭Session。
-
即使事务中只包含只读操作,也应该在事务执行成功后提交事务,并且在事务执行失败时撤销事务。因为在提交或撤销事务时,数据库会释放事务所占用的资源,有利于提高数据库的运行性能。
-
一个Session可以包含多个Transaction实例,也就是说,一个Session可以对应多个事务。
-
如果在执行Session的一个事务时出现了异常,就必须立即关闭这个Session不能再利用这个Session来执行其他的事务
2、Hibernat持久层运行在一个托管环境中,可以配置使用JTA :
<session-factory> <property name="transaction.factory_class"> org.hibernate.transaction.JTATransactionFactory </property> </session-factory>
// BMT(bean管理事务)
UserTransaction tx = null;
try {
tx = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
tx.begin();
// Do some work on Session bound to transaction
factory.getCurrentSession().persist(...);
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
注:在CMT(容器管理事务)方式下,事务声明是在session bean的部署描述符中,而不需要编程。