日期:2014-05-19  浏览次数:20788 次

hibernate 中多对多关系映射:session中不能save()两个对象
求各位帮忙

测试类如下:
public class Many2Many2 {
public static void main(String args[]){
d();
}
static void d() {
Session s = null;
Transaction ts = null;
try{

Teacher te = new Teacher();
te.setName("te name");

Teacher ta = new Teacher();
ta.setName("ta name");

Student st = new Student();
st.setName("st name");

Student su = new Student();
su.setName("su name");

//Set<Student> stu = new HashSet<Student>();
//stu.add(st);
//stu.add(su);
/*
ta.setStudents(stu);
te.setStudents(stu);*/


s = HibernateUtil.getSession();
ts = s.beginTransaction();
s.save(ta);
s.save(te);
s.save(su);
s.save(st);
ts.commit();
}finally{
if(s!=null)
s.close();
}
}
}

报错如下:
Exception in thread "main" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.sias.Teacher#0]
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:190)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:143)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at com.sias.Many2Many2.d(Many2Many2.java:43)
at com.sias.Many2Many2.main(Many2Many2.java:13)



Student.hbm.xml如下:
<hibernate-mapping
package="com.sias">

<class name="Student">
<id name="id">

</id>

<property name="name"/>
 
<set name="teachers" table="teacher_student">
<key column="student_id"></key>
<many-to-many class="Teacher" column="teacher_id"/>

</set>
</class>

</hibernate-mapping>

Teacher.hbm.xml 如下:

<hibernate-mapping
package="com.sias">

<class name="Teacher">
<id name="id">

</id>

<property name="name"/>
 
<set name="students" table="teacher_student">
<key column="teacher_id"></key>
<many-to-many class="Student" column="student_id"/>

</set>
</class>
</hibernate-mapping>



------解决方案--------------------
http://hi.baidu.com/