本文共 1410 字,大约阅读时间需要 4 分钟。
Hibernate 的持久化上下文提供了一系列的事务API,这些事务API,只是为了分离上层应用与底层数据库,便于将来可能的数据库迁移。Hibernate本身没有提供任何新的事务特性。
使用Hibernate的API的步骤如下:
Hibernate的API提供如下事务操作:
Hibernate使用JDBC事务或JTA事务(BMT)示例如下:
Session session = sessionFactory.openSession();try { // calls Connection#setAutoCommit( false ) to // signal start of transaction session.getTransaction().begin(); session.createQuery( "UPDATE customer set NAME = 'Sir. '||NAME" ) .executeUpdate(); // calls Connection#commit(), if an error // happens we attempt a rollback session.getTransaction().commit();}catch ( Exception e ) { // we may need to rollback depending on // where the exception happened if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) { session.getTransaction().rollback(); } // handle the underlying error}finally { session.close();}Hibernate使用JTA事务(CMT)示例如下:
Session session = sessionFactory.openSession();try { Number customerCount = (Number) session.createQuery( "select count(c) from Customer c" ).uniqueResult();}catch ( Exception e ) { // handle the underlying error}finally { session.close();}
转载地址:http://milai.baihongyu.com/