spring / hibernate:每次VS getCurrentSession打开/关闭会话 [英] spring/hibernate: open/close session each time VS getCurrentSession
问题描述
这些方法之间有什么区别,哪一个更好?到目前为止,我的代码片段如下:
What are the differences between these approaches and which one is better? Until now I'm having pieces of code like the following:
public void delete(Song song) {
session = sessionFactory.getCurrentSession();
session.delete(song);
session.flush();
}
但上面的代码运行时记录并不总是被删除= 1永远不会被删除,其他ID将始终被删除)。我读到,保持打开的会话加快了应用程序的速度 - 这就是为什么我共享会话对象。我的业务对象通过DI获得会话工厂:
but the record is not always deleted when above code is run (precisely: id=1 is never deleted and other ids are deleted always). I read that keeping opened session speeds up the application a little bit - that's why I'm sharing the session object. My business object get the session factory via DI:
@Autowired
private SessionFactory sessionFactory;
Session session = null;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
推荐答案
,我得出的结论是最好的策略是将Hibernate会话的生命周期与单个事务的持续时间相匹配。根据您的具体需求,您可能还需要做其他事情,但我敢打赌,拟议中的startegy可以在95%的实际案例中发挥作用。
Based on my expereince with Hibernate, I came to the conclusion that the best strategy is to match the Hibernate session life span with the duration of a single transaction. Based on your specific needs, you might have to do something else, but I bet the proposed startegy would work in 95% of practical cases.
这篇关于spring / hibernate:每次VS getCurrentSession打开/关闭会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!