直接使用Hibernate的简单讲解

来源:岁月联盟 编辑:zhuzhu 时间:2009-09-22

学习Hibernate时,经常会遇到直接使用Hibernate问题,这里将介绍直接使用Hibernate问题的解决方法。

在直接使用Hibernate时,要在事务结束的时候,写上一句:tx.commit(),这个commit()的源码为:

  1. public void commit() throws HibernateException {  
  2. if (!begun) {  
  3. throw new TransactionException("Transaction not successfully started");  
  4. }  
  5.  
  6. log.debug("commit");  
  7.  
  8. if (!transactionContext.isFlushModeNever() && callback) {  
  9. transactionContext.managedFlush(); // if an exception occurs during  
  10. // flush, user must call  
  11. // rollback()  
  12. }  
  13.  
  14. notifyLocalSynchsBeforeTransactionCompletion();  
  15. if (callback) {  
  16. jdbcContext.beforeTransactionCompletion(this);  
  17. }  
  18.  
  19. try {  
  20. commitAndResetAutoCommit();
  21. //重点代码,它的作用是提交事务,并把connection的autocommit属性恢复为true  
  22. log.debug("committed JDBC Connection");  
  23. committed = true;  
  24. if (callback) {  
  25. jdbcContext.afterTransactionCompletion(true, this);  
  26. }  
  27. notifyLocalSynchsAfterTransactionCompletion(Status.STATUS_COMMITTED);  
  28. } catch (SQLException e) {  
  29. log.error("JDBC commit failed", e);  
  30. commitFailed = true;  
  31. if (callback) {  
  32. jdbcContext.afterTransactionCompletion(false, this);  
  33. }  
  34. notifyLocalSynchsAfterTransactionCompletion(Status.STATUS_UNKNOWN);  
  35. throw new TransactionException("JDBC commit failed", e);  
  36. } finally {  
  37. closeIfRequired();  
  38. }  

上面代码中,commitAndResetAutoCommit()方法的源码如下:

  1. private void commitAndResetAutoCommit() throws SQLException {  
  2. try {  
  3. jdbcContext.connection().commit();  
  4. //这段不用说也能理解了  
  5. } finally {  
  6. toggleAutoCommit();  
  7. //这段的作用是恢复connection的autocommit属性为true  
  8. }  

上述代码的toggleAutoCommit()源代码如下:

  1. private void toggleAutoCommit() {  
  2. try {  
  3. if (toggleAutoCommit) {  
  4. log.debug("re-enabling autocommit");  
  5. jdbcContext.connection().setAutoCommit(true);  
  6. //这行代码的意义很明白了吧  
  7. }  
  8. } catch (Exception sqle) {  
  9. log.error("Could not toggle autocommit", sqle);  
  10. }  

因此,如果你是直接使用Hibernate,并手动管理它的session,并手动开启事务关闭事务的话,完全可以保证你的事务(好像完全是废话)。