我正在使用以下方法来解决hibernate中唯一的延迟初始化问题。请告诉我它是否可以工作。
由于某些原因,我必须在我的持久层中强制执行事务处理。
public class CourseDAO {
Session session = null;
public CourseDAO()
{
this.session = this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public Course findByID(int cid){
Course crc = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery("from Course as course where course.cid = "+cid+" ");
crc = (Course) q.uniqueResult();
//note that i am not commiting my transcation here.Because If i do that i will not be able to
//do lazy fetch
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
return crc;
}
}
在过滤器中,我正在使用以下代码
session = HibernateUtil.getSessionFactory().getCurrentSession();
if(session.isOpen())
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
这种方法正确吗?
可以有什么问题吗
最佳答案
您能解释一下为什么您需要在您的存储库中进行交易吗?问题在于它们的粒度是如此之细,因此您不会从会话缓存中获得任何好处
那么您要在那里打开交易,但要在过滤器中关闭交易。如果您访问服务中的多个存储库,会发生什么?也许我不明白您的意思,但我认为您需要重新考虑迫使您在存储库中管理交易的原因
关于java - 在 View 中 hibernate Open Session,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/782272/