HibernateUtils整合工具類


 1 import org.hibernate.Session;
 2 import org.hibernate.SessionFactory;
 3 import org.hibernate.cfg.Configuration;
 4 
 5 public class HibernateUtils {
 6 
 7 // 1.創建工廠對象;
 8 private static SessionFactory sessionFactory;
 9 
10 // 2.初始化工廠對象;
11 static {
12 sessionFactory = new Configuration().configure().buildSessionFactory();
13 }
14 
15 // 3.獲得Session;
16 public static Session getSession() {
17 
18 return sessionFactory.openSession();
19 
20 }
21 
22 }

 

 

以上代碼獲得會話工廠類,但是會話開始之前要有一個開啟事務,所以兩者不能在一起使用,只能獲取Session之后再開啟事務;

For Example;

public class Demo1 {

@Test
public void demo1() {
//	// 5.開啟事務;

Session openSession = null;
Transaction beginTransaction = null;
try {
openSession = HibernateUtils.getSession();
beginTransaction = openSession.beginTransaction();
// 6.操作數據庫;
Query createQuery = openSession.createQuery("from Admin");
System.out.println(createQuery.list());
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 7. 提交事務;
beginTransaction.commit();
// 8 關閉資源;
openSession.close();
}

}

}

  

 源代碼;

 1 import org.hibernate.Query;
 2 import org.hibernate.SessionFactory;
 3 import org.hibernate.Transaction;
 4 import org.hibernate.cfg.Configuration;
 5 import org.hibernate.classic.Session;
 6 import org.junit.Test;
 7 
 8 public class Demo1 {
 9     
10     
11     @Test
12     public void demo1() {
13         
14         // 1.獲取加載配置資源的對象;
15         Configuration configuration = new Configuration();
16         // 2.加載資源配置;
17         // 當不寫路徑的時候,默認資源文件在src目錄下;
18         configuration.configure();
19         
20         // 3.創建Session會話對象;
21         SessionFactory sessionFactory = configuration.buildSessionFactory();
22         // 4.開啟會話;
23         Session openSession = sessionFactory.openSession();
24         // 5.開啟事務;
25         Transaction beginTransaction = openSession.beginTransaction();
26         // 6.操作數據庫;
27         Query createQuery = openSession.createQuery("from Admin");
28         
29         System.out.println(createQuery.list().size());
30         // 7. 提交事務;
31         beginTransaction.commit();
32         // 8 關閉資源;
33         openSession.close();
34         sessionFactory.close();
35         
36     }
37     
38 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM