java为什么我得到org。冬眠HibernateeException:未配置CurrentSessionContext
我正在写一个简单的项目,一个用Swing编写的商业应用程序,使用Hibernate作为后端。我来自Spring,它为我提供了使用hibernate和事务的简单方法。无论如何,我设法让Hibernate工作。昨天,在编写代码从DB中删除一个bean时,我得到了以下信息:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
删除代码仅为:
Session sess = HibernateUtil.getSession();
Transaction tx = sess.beginTransaction();
try {
tx.begin();
sess.delete(ims);
} catch (Exception e) {
tx.rollback();
throw e;
}
tx.commit();
sess.flush();
我的HibernateUtil.getSession()
是:
public static Session getSession() throws HibernateException {
Session sess = null;
try {
sess = sessionFactory.getCurrentSession();
} catch (org.hibernate.HibernateException he) {
sess = sessionFactory.openSession();
}
return sess;
}
附加细节:我从不在代码中关闭hibernate会话,只是在应用程序关闭时。这是错的吗?为什么我在delete上得到这个(只有对于那个bean,其他bean可以工作),而在其他操作(Insert、query、update)上没有得到这个
我四处阅读,试图简单地在sessionFactory.getCurrentSessionCall()
中修改我的getSession
方法,但我得到:org.hibernate.HibernateException: No CurrentSessionContext configured!
Hibernat配置:
<hibernate-configuration>
<session-factory >
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/joptel</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">******</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
..mappings..
</session-factory>
</hibernate-configuration>
# 1 楼答案
阅读Contextual Sessions上的参考指南。你必须为此configure some provided or custom strategy。冬眠。cfg。xml,您可以使用
您可能希望使用“thread”作为获取每线程会话的值。当使用Spring时,它会自动将其设置为SpringSessionContext,从而允许Spring轻松地将Hibernate与其事务管理框架集成
如果您熟悉Spring,为什么不在这里使用它来管理Hibernate?你一定已经知道它是多么简单和简单
是的,这是非常错误的。每个未关闭的会话都是一个开放的数据库连接,因此您的应用程序当前正在流失连接
这就是它所说的。您试图对已关联到其他会话的内容执行一些持久性操作(save()、update()、delete())。这就是当您在任何时候随机打开新会话时会发生的情况,这是自SessionFactory以来发生的情况。当未设置“当前会话上下文”时,getCurrentSession()将始终失败。一般来说,从不因为会话不存在而打开会话。你需要有明确的开始和结束会话的策略,并且不要让任何东西在这些“策略”之外打开会话。这肯定会导致资源泄漏和错误,就像您遇到的那样
# 2 楼答案
在使用SpringRemoting和hibernate的门户网站上工作时,我遇到了同样的问题。 只有当被调用的服务方法包含多个使用hibernate会话命中数据库的DAO调用时,才会出现这种问题
解决方案是为具有多个DAO调用的方法设置@Transaction注释。(意味着此方法中的所有DOA调用都应在一个事务下。)
# 3 楼答案
我想问你一件事,你为什么要尝试使用“OpenSession”方法
您不必调用
openSession()
,因为getCurrentSession()
方法始终返回当前会话(如果您已将其配置为线程,则为线程)我明白了!。。。 您必须在hibernate中指定当前上下文。cfg。xml文件
应该是: