还是以前的一个题目,一直没有解决
classroom(班级)与student(学生)一对多双向关系
现在我ClassRoom room=(ClassRoom)session.get(ClassRoom.class,new Integer(1));返回一个持久化对象
接着我有定义了一个临时对象ClassRoom room1=new ClassRoom();现在我想让room.getSet()返回的集合放到room1对象中去;
网上高手说要对room.getSet()这个set克隆,可是最近我一直没有实验成功
public void testAA2(){
HibernateUtil.beginTransaction();
Session session=HibernateUtil.getCurrentSession();
ClassRoom room=(ClassRoom)session.get(ClassRoom.class,new Integer(1));
room.getSet().iterator();
ClassRoom room1=new ClassRoom();
Set set=new HashSet();
try {
room1=(ClassRoom)room.colneObject();
//克隆room
set=room1.getSet();
room1.setName("0003");
room1.setSet(set);
session.save(room1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.getTransaction().commit();
session.close();
}
一直出错,Found shared references to a collection:set
估计还是没有克隆好,我的colneObject()方法是
public class ClassRoom implements java.io.Serializable,java.lang.Cloneable{
private Integer id;
private String name;
private Set set=new HashSet();
public Set getSet() {
return set;
}
public void setSet(Set set) {
this.set = set;
}
public ClassRoom() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object colneObject() throws CloneNotSupportedException{
return super.clone();
}
}
请高手帮我解决一下,谢谢
;;;;;;;;;;;;;;;;
另外我认为还有一种方法可以实现,就是取得room对象,然后关掉session,然后保存,代码如下:
public void testAA3(){
HibernateUtil.beginTransaction();
Session session=HibernateUtil.getCurrentSession();
ClassRoom room=(ClassRoom)session.get(ClassRoom.class,new Integer(1));
room.getSet().iterator();
session.close();
Session session2=HibernateUtil.getCurrentSession();//这样写报错如下:
//org.hibernate.SessionException: Session is closed!...
.....
//Session session2=HibernateUtil.getCurrentSession();////如果这样写报错如下
//org.hibernate.HibernateException: No CurrentSessionContext configured!
....
ClassRoom room1=new ClassRoom();
Set<Student> set2=new HashSet<Student>();
room1.setName("0003");
room1.setSet(room.getSet());
session2.save(room1);
session2.getTransaction().commit();
session2.close();
}
可是这样写还是一直报错,还是一直没有保存成功!!!
哪位好心人指点一下以上两个问题怎么解决呀