简体   繁体   中英

persist method giving PersistentObjectException on trying to persist a new Object

In my below code i am trying to persist a newly created instance of Employee, it is throwing persistantobject exception :

public class abc
{
   public static void main(String as[])
   {
       Configuration cfg= new Configuration();System.out.println("--------------got cfg object-----------");
       cfg = cfg.configure("hibernate.cfg.xml");System.out.println("--------------hbm loaded into cfg-----------");
       SessionFactory sf= cfg.buildSessionFactory();
       Employee item3 = new Employee();
       item3.setEid(420);
       Session session = sf.openSession(); 
       Employee item = (Employee) session.get(Employee.class, new Integer(12));
      // item.setFname("myaim1"); 
      // session.save(item);

     // Integer a= (Integer)session.save(item3);
       //session.persist(item3);
       Transaction tx = session.beginTransaction();
       session.persist(item3);
        tx.commit(); 
       session.close(); // end of first session, item is detached  

   }}

And exception is :

-------------hbm loaded into cfg-----------
Hibernate: select employee0_.eid as eid0_0_, employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.email as email0_0_ from EMPLOYEE3 employee0_ where employee0_.eid=?
Exception in thread "main" org.hibernate.PersistentObjectException: detached entity passed to persist: Employee
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:79)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
    at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
    at abc.main(abc.java:23)

i am using hibernate core ver 4.3. Whats gone wrong ?

Is there any particular reason for using persist() here ? Why are you not using save() ?

Something like this :

Session session = HibernateUtil.getSessionFactory().openSession();

session.beginTransaction();
session.save(item3);
session.getTransaction().commit();

Most probably the error is at the line item3.setEid(420); . I guess you must be using @Id with @GeneratedValue with one of `SEQUENCE/IDENTITY/TABLE/AUTO'. If so, you can comment out this line as try.

If you continue to face the same issue, posting the Employee class would help further debug it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM