我是休眠技术的新手,我正在努力解决以下异常:
org.hibernate.HibernateException:非法尝试将集合与两个打开的会话相关联
当我尝试在我的数据库中创建一个新行时,我得到了这个。
我的设置/代码:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Paramètres de connexion à la base de données -->
<!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property> -->
<!-- <property name="connection.url">jdbc:mysql://localhost:3306/bh</property> -->
<!-- <property name="connection.username">root</property> -->
<!-- <property name="connection.password"></property> -->
<!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/projetForum</property>
<property name="connection.username">postgres</property>
<property name="connection.password">esct</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Comportement pour la conservation des tables -->
<property name="hbm2ddl.auto">update</property>
<!-- Activation : affichage en console, commentées et formatées -->
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- Fichiers à mapper -->
<mapping class="com.forum.beans.Utilisateur" />
<mapping class="com.forum.beans.Topic" />
<mapping class="com.forum.beans.Post" />
</session-factory>
</hibernate-configuration>
会话持有者:
package com.forum.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtils {
private static final SessionFactory sessionFactory;
// Crée une unique instance de la SessionFactory à partir de
// hibernate.cfg.xml
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Problème de configuration : "
+ ex.getMessage(), ex);
}
}
// Renvoie une session Hibernate
public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
}
}
导致错误的代码:
Transaction tx = null;
try {
s = HibernateUtils.getSession();
tx = s.beginTransaction();
s.persist(u);
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
System.out.println(e);
}