Hibernate事務管理

在Hibernate中,可以通過代碼來操作管理事務,如通過

“Transaction tx=session.beginTransactiong();”

開啟一個事務,持久化操作後,通過"tx.commit();" 提交事務;如果事務出現異常,又通過“tx.rollback();"操作來撤銷事務(事務回滾)。

除了在代碼中對事務開啟,提交和回滾操作外,還可以在hibernate的配置文件中對事務進行配置。配置文件中,可以設置事務的隔離級別。其具體的配置方法是在hibernate.cfg.xml文件中的

<session-factory>標籤元素中進行的。配置方法如下所示。/<session-factory>

<property>4/<property>

到這裡我們已經設置了事務的隔離級別,那麼我們在真正進行事務管理的時候,需要考慮事務的應用場景,也就是說我們的事務控制不應該是在DAO層實現的,應該在Service層實現,並且在Service中調用多個DAO實現一個業務邏輯的操作。具體操作如下顯示:

Hibernate事務管理

其實最主要的是如何保證在Service中開啟的事務時使用的Session對象和DAO中多個操作使用的是同一個Session對象。

其實有兩種辦法可以實現:

1. 可以在業務層獲取到Session,並將Session作為參數傳遞給DAO。

2. 可以使用ThreadLocal將業務層獲取的Session綁定到當前線程中,然後再DAO中獲取Session的時候,都從當前線程中獲取。

其實使用第二種方式肯定是最優方案,那麼具體的實現已經不用我們來完成了,hibernate的內部已經將這個事情做完了。我們只需要完成一段配置即可。

Hibernate5中自身提供了三種管理Session對象的方法

Session對象的生命週期與本地線程綁定

Session對象的生命週期與JTA事務綁定

Hibernate委託程序管理Session對象的生命週期

在Hibernate的配置文件中,hibernate.current_session_context_class屬性用於指定Session管理方式,可選值包括:

1. thread:Session對象的生命週期與本地線程綁定(推薦)

2. jta:Session對象的生命週期與JTA事務綁定

3. managed:hibernate委託程序來管理Session對象的生命週期。

在hibernate.cfg.xml中進行如下配置:

<property>thread/<property>

Hibernate提供sessionFactory.getCurrentSession()創建一個session和ThreadLocal綁定方法。

在HibernateUtils工具類中更改getCurrentSession方法:

public static Session getCurrentSession() {

return sessionFactory.getCurrentSession();

}

而且Hibernate中提供的這個與線程綁定的session可以不用關閉,當線程執行結束後,就會自動關閉了。

所以最終的配置文件如下:

Hibernate事務管理

Hibernate事務管理

 1 
2
3 <hibernate-configuration>
4 <session-factory>
5 <property>com.mysql.jdbc.Driver/<property>
6 <property>jdbc:mysql:///day24_db/<property>
7 <property>root/<property>
8 <property>toor/<property>
9 <property>org.hibernate.dialect.MySQLDialect/<property>
10 <property>true/<property>
11 <property>true/<property>
12 <property>update/<property>
13
24
25
26 <property>4/<property>
27
28 <property>thread/<property>
29 <mapping>
30 /<session-factory>
31 /<hibernate-configuration>
 1 package cn.eagle.utils;
2
3 import org.hibernate.Session;
4 import org.hibernate.SessionFactory;
5 import org.hibernate.cfg.Configuration;
6
7 public class HibernateUtils {
8
9 private static final Configuration configuration;
10 private static final SessionFactory sessionFactory;
11
12 static {
13 configuration = new Configuration().configure();
14 sessionFactory = configuration.buildSessionFactory();
15 }
16
17 public static Session getCurrentSession() {
18 return sessionFactory.getCurrentSession();
19 }
20 }


分享到:


相關文章: