日期:2014-05-19 浏览次数:20768 次
.... 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(); } }
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; } }
[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)