将CRUD封装到一个工具类中

 1 package org.zln.hibernate.utils;
 2 
 3 
 4 import org.hibernate.Session;
 5 import org.hibernate.SessionFactory;
 6 import org.hibernate.Transaction;
 7 import org.hibernate.cfg.Configuration;
 8 
 9 import java.io.Serializable;
10 
11 /**
12  * Created by coolkid on 2015/6/14 0014.
13  */
14 public final class HibernateUtils {
15 
16     private static Configuration configuration = new Configuration();
17     private static SessionFactory sessionFactory;
18     private static final String PATH = "hibernate.cfg.xml";
19 
20     private HibernateUtils(){}
21 
22     static {
23         /*初始化Hibernate*/
24         configuration.configure(PATH);
25         sessionFactory = configuration.buildSessionFactory();
26     }
27 
28     public static SessionFactory getSessionFactory(){
29         return sessionFactory;
30     }
31 
32     public static Session getSession(){
33         return sessionFactory.openSession();
34     }
35 
36     public static void add(Object o){
37         Session session = null;
38         Transaction transaction = null;
39         try {
40             session = HibernateUtils.getSession();
41             transaction = session.beginTransaction();
42             session.save(o);
43             session.flush();
44             transaction.commit();
45         }finally {
46             if (session != null){
47                 session.close();
48             }
49         }
50     }
51 
52     public static void update(Object o){
53         Session session = null;
54         Transaction transaction = null;
55         try {
56             session = HibernateUtils.getSession();
57             transaction = session.beginTransaction();
58             session.update(o);
59             transaction.commit();
60         }finally {
61             if (session != null){
62                 session.close();
63             }
64         }
65     }
66 
67     public static void delete(Object o){
68         Session session = null;
69         Transaction transaction = null;
70         try {
71             session = HibernateUtils.getSession();
72             transaction = session.beginTransaction();
73             session.delete(o);
74             transaction.commit();
75         }finally {
76             if (session != null){
77                 session.close();
78             }
79         }
80     }
81 
82     public static Object getObject(Class clazz,Serializable id){
83         Object o = null;
84         Session session = null;
85         try {
86             session = HibernateUtils.getSession();
87             o = session.get(clazz,id);
88         }finally {
89             if (session!=null){
90                 session.close();
91             }
92         }
93         return o;
94     }
95 }

 

转载于:https://www.cnblogs.com/sherrykid/p/4575688.html

你可能感兴趣的:(将CRUD封装到一个工具类中)