程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> hibernate3學習筆記(六) Session管理

hibernate3學習筆記(六) Session管理

編輯:關於JAVA

請注意,在hibernate中SessionFactory是被設計成線程安全(Thread-safe)的,遺憾的是,Session卻線程不安全。

這就意味著:有可能多個線程共享並操作同一個Session從而很容易使數據混亂。

解決的辦法如下:(其實hibernate的文檔中早已經提過了)

新建HibernateUtil類:

1.import org.apache.commons.logging.Log;
2.import org.apache.commons.logging.LogFactory;
3.import org.hibernate.*;
4.import org.hibernate.cfg.*;
5.
6.public class HibernateUtil {
7. private static Log log = LogFactory.getLog(HibernateUtil.class);
8. private static final SessionFactory sessionFactory;
9. 10. static {
11. try {
12. // Create the SessionFactory 13. sessionFactory = new Configuration().configure()
14. .buildSessionFactory();
15. } catch (Throwable ex) {
16. // Make sure you log the exception, as it might be swallowed 17. log.error("Initial SessionFactory creation failed.", ex);
18. throw new ExceptionInInitializerError(ex);
19. }
20. }
21. 22. public static final ThreadLocal session = new ThreadLocal();
23. 24. public static Session currentSession() {
25. Session s = (Session) session.get();
26. 27. // Open a new Session, if this Thread has none yet 28. if (s == null) {
29. s = sessionFactory.openSession();
30. session.set(s);
31. }
32. 33. return s;
34. }
35. 36. public static void closeSession() {
37. Session s = (Session) session.get();
38. 39. if (s != null) {
40. s.close();
41. }
42. 43. session.set(null);
44. }
45.}

這樣,在程序中可這樣調用:

1.Session session = HibernateUtil.currentSession();
2.User user = (User) session.load(User.class, new Integer(1));
3.System.out.println(user.getName());
4.HibernateUtil.closeSession();

在web應用中,可以借由Filter來進行session管理。在需要session的時候開啟session,在request結束之後關閉session。

HibernateSessionUtil.java

1.import java.io.Serializable;
2.
3.import net.sf.hibernate.HibernateException;
4.import net.sf.hibernate.Session;
5.import net.sf.hibernate.SessionFactory;
6.import net.sf.hibernate.Transaction;
7. 8.public class HibernateSessionUtil implements Serializable
9.{
10. public static final ThreadLocal tLocalsess = new ThreadLocal();
11. 12. public static final ThreadLocal tLocaltx = new ThreadLocal();
13. 14. /*
15. * getting the thread-safe session for using
16. */17. public static Session currentSession(){
18. Session session = (Session) tLocalsess.get();
19. 20. //open a new one, if none can be found. 21. try{
22. if (session == null){
23. session = openSession();
24. tLocalsess.set(session);
25. }
26. }catch (HibernateException e){
27. throw new InfrastructureException(e);
28. }
29. return session;
30. }
31. 32. /*
33. * closing the thread-safe session
34. */ 35. public static void closeSession(){
36. 37. Session session = (Session) tLocalsess.get();
38. tLocalsess.set(null);
39. try{
40. if (session != null && session.isOpen()){
41. session.close();
42. }
43. 44. }catch (HibernateException e){
45. throw new InfrastructureException(e);
46. }
47. }
48. 49. /*
50. * begin the transaction
51. */ 52. public static void beginTransaction(){
53. Transaction tx = (Transaction) tLocaltx.get();
54. try{
55. if (tx == null){
56. tx = currentSession().beginTransaction();
57. tLocaltx.set(tx);
58. }
59. }catch (HibernateException e){
60. throw new InfrastructureException(e);
61. }
62. }
63. 64. /*
65. * close the transaction
66. */ 67. public static void commitTransaction(){
68. Transaction tx = (Transaction) tLocaltx.get();
69. try{
70. if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
71. tx.commit();
72. tLocaltx.set(null);
73. }catch (HibernateException e){
74. throw new InfrastructureException(e);
75. }
76. }
77. 78. /*
79. * for rollbacking
80. */ 81. public static void rollbackTransaction(){
82. Transaction tx = (Transaction) tLocaltx.get();
83. try{
84. tLocaltx.set(null);
85. if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
86. tx.rollback();
87. }
88. }catch (HibernateException e){
89. throw new InfrastructureException(e);
90. }
91. }
92. 93. private static Session openSession() throws HibernateException{
94. return getSessionFactory().openSession();
95. }
96. 97. private static SessionFactory getSessionFactory() throws HibernateException{
98. return SingletonSessionFactory.getInstance();
99. }
100.}

filter中則:

1.public class HibernateSessionCloser implements Filter{
2.
3. protected FilterConfig filterConfig = null;
4. 5. public void init(FilterConfig filterConfig)throws ServletException{
6. this.filterConfig = filterConfig;
7. }
8.
9. public void destroy(){
10. this.filterConfig = null;
11. }
12. 13. public void doFilter(ServletRequest request, ServletResponse response,
14. FilterChain chain)
15. throws IOException, ServletException {
16. try{
17. chain.doFilter(request, response);
18. }
19. finally{
20. try{
21. HibernateSessionUtil.commitTransaction();
22. }catch (InfrastructureException e){
23. HibernateSessionUtil.rollbackTransaction();
24. }finally{
25. HibernateSessionUtil.closeSession();
26. }
27. }
28. 29. }
30.}

然後在操作數據庫前加上

HibernateSessionUtil.beginTransaction();

HibernateSessionUtil.currentSession();//取得Session

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved