Hibernate的CRUD操作
2009-09-08 21:52 Jvpy 阅读(269) 评论(0) 收藏 举报
Hibernate的CRUD操作:

HibernateUtil.java
1 package cn.jvpy.hibernate;
2
3 import org.hibernate.HibernateException;
4 import org.hibernate.Session;
5 import org.hibernate.SessionFactory;
6 import org.hibernate.Transaction;
7
8 public final class HibernateUtil {
9 /**
10 * <p>
11 * Retrieves the session.
12 * </p>
13 *
14 * @param sf the <code>SessionFactory</code> instance.
15 *
16 * @return the retrieved session.
17 *
18 * @throws IllegalStateException if the sf is not set (null value).
19 * @throws HibernateException if any error occurs when locating a suitable current session.
20 */
21 public static Session getSession(SessionFactory sf) {
22 if (sf == null) {
23 throw new IllegalStateException("The session factory is not set.");
24 }
25
26 return sf.openSession();
27 }
28
29 /**
30 * <p>
31 * Creates the entity in the persistence.
32 * </p>
33 *
34 * @param <T> the entity type.
35 * @param session the current session.
36 * @param entity the entity to be created.
37 * @param clazz the entity class.
38 *
39 * @return the updated instance of the created entity.
40 *
41 * @throws HibernateException if any error occurs when accessing the persistence.
42 */
43 @SuppressWarnings("unchecked")
44 public static <T> T createEntity(Session session, Class<T> clazz, Object entity) {
45 Transaction tx = null;
46 T ret = null;
47 try {
48 tx = session.beginTransaction();
49 // persist the given entity
50 ret = (T) session.get(clazz, session.save(entity));
51
52 // commit the transaction
53 tx.commit();
54
55 // the persisted entity
56 return ret;
57 } catch (HibernateException e) {
58 if (tx != null) {
59 tx.rollback();
60 }
61
62 throw e;
63 } finally {
64 closeSession(session);
65 }
66 }
67
68 /**
69 * <p>
70 * Retrieves the entity from the persistence by the given id.
71 * </p>
72 *
73 * @param <T> the entity type.
74 * @param session the current session.
75 * @param id the identification number of the entity to be retrieved.
76 * @param clazz the entity class
77 *
78 * @return the retrieved entity. It can be null if the entity is not found.
79 *
80 * @throws HibernateException if any error occurs when accessing the persistence.
81 */
82 @SuppressWarnings("unchecked")
83 public static <T> T getEntityById(Session session, Class<T> clazz, long id) {
84 return (T) session.get(clazz, id);
85 }
86
87 /**
88 * <p>
89 * Updates the entity to the persistence.
90 * </p>
91 *
92 * @param <T> the entity type.
93 * @param session the current session.
94 * @param entity the entity to be updated.
95 *
96 * @return the updated persistent instance.
97 *
98 * @throws HibernateException if any error occurs when accessing the persistence.
99 */
100 @SuppressWarnings("unchecked")
101 public static <T> T updateEntity(Session session, Object entity) {
102 Transaction tx = null;
103 try {
104 tx = session.beginTransaction();
105
106 // update the entity in the persistence
107 T ret = (T) session.merge(entity);
108
109 // commit the transaction
110 tx.commit();
111
112 return ret;
113 } catch (HibernateException e) {
114 if (tx != null) {
115 tx.rollback();
116 }
117
118 throw e;
119 } finally {
120 closeSession(session);
121 }
122 }
123
124 /**
125 * <p>
126 * Deletes the entity from the persistence.
127 * </p>
128 *
129 * @param session the current session.
130 * @param entity the entity to be deleted.
131 *
132 * @throws HibernateException if any error occurs when accessing the persistence.
133 */
134 public static void deleteEntity(Session session, Object entity) {
135 Transaction tx = null;
136 try {
137 tx = session.beginTransaction();
138
139 // delete the entity from persistence
140 session.delete(entity);
141
142 // commit the transaction
143 tx.commit();
144 } catch (HibernateException e) {
145 if (tx != null) {
146 tx.rollback();
147 }
148
149 throw e;
150 } finally {
151 closeSession(session);
152 }
153 }
154
155 /**
156 * <p>
157 * Silently closes the session.
158 * </p>
159 *
160 * @param session the session to be closed.
161 */
162 private static void closeSession(Session session) {
163 if (session != null) {
164 // silently close the session
165 try {
166 session.close();
167 } catch (HibernateException e) {
168 // ignore
169 }
170 }
171 }
172 }
173
有些方法可以不用传入clazz,entity.getClass()可以获得其class.

Code
1 public static User getUser(Session session, String name) {
2 Query query = session.createQuery("FROM User u where u.name=:name");
3 query.setString("name", name);
4 return (User) query.list();
5

Code
1 public static User getUser1(Session session, String name) {
2 Criteria criteria = session.createCriteria(User.class);
3 criteria.add(Restrictions.eq("name", name));
4 return (User) criteria.list();
5



1 package cn.jvpy.hibernate;
2
3 import org.hibernate.HibernateException;
4 import org.hibernate.Session;
5 import org.hibernate.SessionFactory;
6 import org.hibernate.Transaction;
7
8 public final class HibernateUtil {
9 /**
10 * <p>
11 * Retrieves the session.
12 * </p>
13 *
14 * @param sf the <code>SessionFactory</code> instance.
15 *
16 * @return the retrieved session.
17 *
18 * @throws IllegalStateException if the sf is not set (null value).
19 * @throws HibernateException if any error occurs when locating a suitable current session.
20 */
21 public static Session getSession(SessionFactory sf) {
22 if (sf == null) {
23 throw new IllegalStateException("The session factory is not set.");
24 }
25
26 return sf.openSession();
27 }
28
29 /**
30 * <p>
31 * Creates the entity in the persistence.
32 * </p>
33 *
34 * @param <T> the entity type.
35 * @param session the current session.
36 * @param entity the entity to be created.
37 * @param clazz the entity class.
38 *
39 * @return the updated instance of the created entity.
40 *
41 * @throws HibernateException if any error occurs when accessing the persistence.
42 */
43 @SuppressWarnings("unchecked")
44 public static <T> T createEntity(Session session, Class<T> clazz, Object entity) {
45 Transaction tx = null;
46 T ret = null;
47 try {
48 tx = session.beginTransaction();
49 // persist the given entity
50 ret = (T) session.get(clazz, session.save(entity));
51
52 // commit the transaction
53 tx.commit();
54
55 // the persisted entity
56 return ret;
57 } catch (HibernateException e) {
58 if (tx != null) {
59 tx.rollback();
60 }
61
62 throw e;
63 } finally {
64 closeSession(session);
65 }
66 }
67
68 /**
69 * <p>
70 * Retrieves the entity from the persistence by the given id.
71 * </p>
72 *
73 * @param <T> the entity type.
74 * @param session the current session.
75 * @param id the identification number of the entity to be retrieved.
76 * @param clazz the entity class
77 *
78 * @return the retrieved entity. It can be null if the entity is not found.
79 *
80 * @throws HibernateException if any error occurs when accessing the persistence.
81 */
82 @SuppressWarnings("unchecked")
83 public static <T> T getEntityById(Session session, Class<T> clazz, long id) {
84 return (T) session.get(clazz, id);
85 }
86
87 /**
88 * <p>
89 * Updates the entity to the persistence.
90 * </p>
91 *
92 * @param <T> the entity type.
93 * @param session the current session.
94 * @param entity the entity to be updated.
95 *
96 * @return the updated persistent instance.
97 *
98 * @throws HibernateException if any error occurs when accessing the persistence.
99 */
100 @SuppressWarnings("unchecked")
101 public static <T> T updateEntity(Session session, Object entity) {
102 Transaction tx = null;
103 try {
104 tx = session.beginTransaction();
105
106 // update the entity in the persistence
107 T ret = (T) session.merge(entity);
108
109 // commit the transaction
110 tx.commit();
111
112 return ret;
113 } catch (HibernateException e) {
114 if (tx != null) {
115 tx.rollback();
116 }
117
118 throw e;
119 } finally {
120 closeSession(session);
121 }
122 }
123
124 /**
125 * <p>
126 * Deletes the entity from the persistence.
127 * </p>
128 *
129 * @param session the current session.
130 * @param entity the entity to be deleted.
131 *
132 * @throws HibernateException if any error occurs when accessing the persistence.
133 */
134 public static void deleteEntity(Session session, Object entity) {
135 Transaction tx = null;
136 try {
137 tx = session.beginTransaction();
138
139 // delete the entity from persistence
140 session.delete(entity);
141
142 // commit the transaction
143 tx.commit();
144 } catch (HibernateException e) {
145 if (tx != null) {
146 tx.rollback();
147 }
148
149 throw e;
150 } finally {
151 closeSession(session);
152 }
153 }
154
155 /**
156 * <p>
157 * Silently closes the session.
158 * </p>
159 *
160 * @param session the session to be closed.
161 */
162 private static void closeSession(Session session) {
163 if (session != null) {
164 // silently close the session
165 try {
166 session.close();
167 } catch (HibernateException e) {
168 // ignore
169 }
170 }
171 }
172 }
173
hibernate实现分页:
1 query.setFirstResult(0);//从第0条记录开始取
2 query.setMaxResults(10);//取10条
2 query.setMaxResults(10);//取10条
Query操作:
1 public static User getUser(Session session, String name) {
2 Query query = session.createQuery("FROM User u where u.name=:name");
3 query.setString("name", name);
4 return (User) query.list();
5
Criteria操作:
1 public static User getUser1(Session session, String name) {
2 Criteria criteria = session.createCriteria(User.class);
3 criteria.add(Restrictions.eq("name", name));
4 return (User) criteria.list();
5
Criteria和Query具有很多相同的接口,使用Criteria的好处是可以避免学习HQL的语法,弊端是没有Query功能强大。
官方推荐用Query。
Session.load(clazz, id)采取lazy加载策略,Session.get(clazz, id)不是lazy加载。
浙公网安备 33010602011771号