当前位置: 代码迷 >> J2EE >> hibernate奇怪的有关问题
  详细解决方案

hibernate奇怪的有关问题

热度:44   发布时间:2016-04-22 01:50:55.0
hibernate奇怪的问题?
先上代码^_^
Java code
....         User user = new User();    user.setUser_name("111");    user.setUser_pwd("222");    save(user);      User user1 = (User)user.clone();          System.out.println(user1.getUser_name());    //①         persist(user1); //②.....            //通过save()添加对象    public static void save(Object obj) throws HibernateException{        try{            session = HibernateFactory.getSession();            //tran = session.beginTransaction();            session.save(obj);            //tran.commit();        }catch(HibernateException e){            if(tran!=null)                tran.rollback();            throw e;        }finally{            close();        }    }        //通过persist()添加对象    public static void persist(Object obj) throws HibernateException{        try{            session = HibernateFactory.getSession();            //tran = session.beginTransaction();            session.persist(obj);            //tran.commit();        }catch(HibernateException e){            if(tran!=null)                tran.rollback();            throw e;        }finally{            close();        }    }


User类:
Java code
package com.hibernate.bean;import java.util.Date;public class User implements Cloneable {    private int id;    private String user_name;    private String user_pwd;    private Date   birthday;         .....      public Object clone(){        User user = null;        try{            user = (User)super.clone();        }catch(CloneNotSupportedException e){            e.printStackTrace();        }        return user;    }}


问题:
在测试save()与persist()的过程中,我使用到了clone(),①处有值,但是②处却抛出异常,如下:
Java code
     [java] Exception in thread "main" org.hibernate.PersistentObjectException:detached entity passed to persist: com.hibernate.bean.User     [java]     at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:102)     [java]     at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)     [java]     at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:645)     [java]     at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:619)     [java]     at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:623)     [java]     at com.hibernate.test.Hibernate2Test.persist(Unknown Source)     [java]     at com.hibernate.test.Hibernate2Test.main(Unknown Source)


请问这是什么原因?

------解决方案--------------------
哈哈哈。。。
------解决方案--------------------
pass
------解决方案--------------------
探讨
Java code
User user=new User();
user.setUser_name("111");
user.setUser_pwd("222");
User user1= (User)user.clone();

save(user);// User user1 = (User)user.clone(); 这里的user的id已经存在了,把这句移¡­

------解决方案--------------------
探讨
楼下的哥们送分你啦~~
  相关解决方案