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

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:6
45)
     [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已经存在了,把这句移¡­

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