Hibernate 打开/关闭会话,DAO 的正确方法
我已经编写了这个 Hibernate 对象 DAO,但是使用这种方法,它使用每次更新会话的方法(我认为这是不对的)。
我认为它不正确的原因是我的 User 类遇到了问题,该类包含延迟获取的集合。从 DAO 检索每个用户时,会话将关闭。因此我无法获得我的收藏。
有时,由于对象已分离,它还会对表进行大量不必要的更新。
那么有什么方法可以修复我的 DAO,例如使用 getCurrentSession() 吗?
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.test.util.DataAccessLayerException;
import org.test.util.HibernateUtil;
public abstract class AbstractDao {
protected Session session;
protected Transaction tx;
public AbstractDao() {
HibernateUtil.buildIfNeeded();
}
protected void saveOrUpdate(Object obj) {
try {
startOperation();
session.saveOrUpdate(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
}
protected void delete(Object obj) {
try {
startOperation();
session.delete(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
}
protected Object find(Class clazz, Long id) {
Object obj = null;
try {
startOperation();
obj = session.load(clazz, id);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
return obj;
}
protected List findAll(Class clazz) {
List objects = null;
try {
startOperation();
Query query = session.createQuery("from " + clazz.getName());
objects = query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
return objects;
}
protected void handleException(HibernateException e) throws DataAccessLayerException {
HibernateUtil.rollback(tx);
throw new DataAccessLayerException(e);
}
protected void startOperation() throws HibernateException {
session = HibernateUtil.openSession();
tx = session.beginTransaction();
}
}
HibernateUtil
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static SessionFactory sessionFactory;
private static SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
public static SessionFactory buildIfNeeded()
throws DataAccessLayerException {
if (sessionFactory != null) {
return sessionFactory;
}
try {
return configureSessionFactory();
} catch (HibernateException e) {
throw new DataAccessLayerException(e);
}
}
public static SessionFactory buildSessionFactory()
throws HibernateException {
if (sessionFactory != null) {
closeFactory();
}
return configureSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session openSession() throws HibernateException {
buildIfNeeded();
return sessionFactory.openSession();
}
public static void closeFactory() {
if (sessionFactory != null) {
try {
sessionFactory.close();
} catch (HibernateException ignored) {
log.error("Couldn't close SessionFactory", ignored);
}
}
}
public static void close(Session session) {
if (session != null) {
try {
session.close();
} catch (HibernateException ignored) {
log.error("Couldn't close Session", ignored);
}
}
}
public static void rollback(Transaction tx) {
try {
if (tx != null) {
tx.rollback();
}
} catch (HibernateException ignored) {
log.error("Couldn't rollback Transaction", ignored);
}
}
}
I have written this Hibernate object DAO, however with this approach, it is using session per update approach (which I don't think it's right).
The reason why I don't think its right because I am running into problems with my User class, which contains collections that are lazily fetched. Since when retrieving each User from the DAO, the session is closed. Therefore I cannot get my collections.
From time to time, it is also doing a lot of unnecessary updates to the table because the object is detached.
So are there any ways of fixing my DAO, like using getCurrentSession()?
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.test.util.DataAccessLayerException;
import org.test.util.HibernateUtil;
public abstract class AbstractDao {
protected Session session;
protected Transaction tx;
public AbstractDao() {
HibernateUtil.buildIfNeeded();
}
protected void saveOrUpdate(Object obj) {
try {
startOperation();
session.saveOrUpdate(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
}
protected void delete(Object obj) {
try {
startOperation();
session.delete(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
}
protected Object find(Class clazz, Long id) {
Object obj = null;
try {
startOperation();
obj = session.load(clazz, id);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
return obj;
}
protected List findAll(Class clazz) {
List objects = null;
try {
startOperation();
Query query = session.createQuery("from " + clazz.getName());
objects = query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateUtil.close(session);
}
return objects;
}
protected void handleException(HibernateException e) throws DataAccessLayerException {
HibernateUtil.rollback(tx);
throw new DataAccessLayerException(e);
}
protected void startOperation() throws HibernateException {
session = HibernateUtil.openSession();
tx = session.beginTransaction();
}
}
HibernateUtil
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static SessionFactory sessionFactory;
private static SessionFactory configureSessionFactory()
throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
public static SessionFactory buildIfNeeded()
throws DataAccessLayerException {
if (sessionFactory != null) {
return sessionFactory;
}
try {
return configureSessionFactory();
} catch (HibernateException e) {
throw new DataAccessLayerException(e);
}
}
public static SessionFactory buildSessionFactory()
throws HibernateException {
if (sessionFactory != null) {
closeFactory();
}
return configureSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session openSession() throws HibernateException {
buildIfNeeded();
return sessionFactory.openSession();
}
public static void closeFactory() {
if (sessionFactory != null) {
try {
sessionFactory.close();
} catch (HibernateException ignored) {
log.error("Couldn't close SessionFactory", ignored);
}
}
}
public static void close(Session session) {
if (session != null) {
try {
session.close();
} catch (HibernateException ignored) {
log.error("Couldn't close Session", ignored);
}
}
}
public static void rollback(Transaction tx) {
try {
if (tx != null) {
tx.rollback();
}
} catch (HibernateException ignored) {
log.error("Couldn't rollback Transaction", ignored);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的方法是将 close 方法添加到您的 DAO(AbstractDao) 中,并将其称为“工作单元”的结尾。
并且,请不要对会话进行静态引用,会话不是线程安全的
这是一个带有示例的精彩解释: Link< /a>
Good approach is to add close method to your DAO(AbstractDao) and call it the end of your "unit of work".
And, please, no static references to session, session is not thread safe
Here is a brilliant explanation with sample: Link
您可以在 HibernateUtil 中保存静态 Session 成员。延迟初始化。
您可以随时关闭会话,但在会话未关闭之前,您将继续使用它。
You can hold a static Session member in HibernateUtil. Lazy initialized.
An close the session whenever you want, but until it isn't closed, you'll keep using it.