-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 12 posts ] 
Author Message
 Post subject: PersistentObjectException: detached entity passed to persist
PostPosted: Wed Jul 11, 2007 4:21 pm 
Newbie

Joined: Wed May 30, 2007 4:45 am
Posts: 8
Location: Cape Town , South Africa
I'm trying to do a simple persisting of an object into a MySQL database , with the following code:

Code:
public static void main(String[] args){
    EntityManager em=JPAUtility.getEntityManager();
    List existing =em.createQuery("select u  from UserBean u where u.userName='foo' and u.password='bar'").getResultList();
    if (existing.size() == 0) {
       System.out.println("User not in db...inserting");
       UserBean user = new UserBean();
       JPAUtility.beginTransaction();
       user.setId(1);
       user.setUserName("foo");
       user.setPassword("bar");
       em.persist(user);
       JPAUtility.commitTransaction();
       System.out.println("Persisted user "+user.getUserName());
      } else {
         System.out.println("Already in db...");
      }
  }



When I run this I'm getting a org.hibernate.PersistentObjectException: detached entity passed to persist .The full stacktrace is as follows:

Code:
User not in db...inserting
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.introspect.tutorial.UserBean
   at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:629)
   at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:218)
   at com.introspect.tutorial.JPAUtility.main(JPAUtility.java:172)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.introspect.tutorial.UserBean
   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 org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:212)
   ... 1 more



Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 11, 2007 5:00 pm 
Red Hat Associate
Red Hat Associate

Joined: Mon Aug 16, 2004 11:14 am
Posts: 253
Location: Raleigh, NC
How is the Entity's PK mapped? Follow the instructions and post all relevant info -- it makes things easier ;)

-Chris

_________________
Chris Bredesen
Senior Software Maintenance Engineer, JBoss


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 11, 2007 5:21 pm 
Newbie

Joined: Wed May 30, 2007 4:45 am
Posts: 8
Location: Cape Town , South Africa
Alright.Am not sure if the following is sufficient :)

Hibernate version: 3.2


UserBean.java

Code:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="USERS")
public class UserBean {


   @Id  @GeneratedValue(strategy=GenerationType.AUTO)
   @Column(name = "ID")
   private int id;

   @Column(name = "USERNAME")
   private String userName;

   @Column(name = "PASSWORD")
   private String password;

   @Transient
   private String verify;

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public String getVerify() {
      return verify;
   }

   public void setVerify(String verify) {
      this.verify = verify;
   }


   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

}


persistence.xml file :
Code:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence     http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
   
   <persistence-unit name="usermanagement" transaction-type="RESOURCE_LOCAL">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.introspect.tutorial.UserBean</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/shoppingcart"/>
         <property name="hibernate.connection.username" value="tutorial"/>
         <property name="hibernate.connection.password" value="tutorial"/>         
        </properties>
   </persistence-unit>

</persistence>


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 11, 2007 8:48 pm 
Beginner
Beginner

Joined: Tue Jun 26, 2007 2:31 pm
Posts: 21
Hi in the code where u are persiting user instance to persist to the db like this
em.persist(user);

try to do this instead of that:
em.save(user);

Let me know if this works well thank you.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jul 12, 2007 3:03 am 
Newbie

Joined: Wed May 30, 2007 4:45 am
Posts: 8
Location: Cape Town , South Africa
sainaveenp wrote:
Hi in the code where u are persiting user instance to persist to the db like this
em.persist(user);

try to do this instead of that:
em.save(user);

Let me know if this works well thank you.




javax.persistence.EntityManager does not have a save(Object o) method.It uses a persist(Object o) method

It looks like its Hibernate persistence provider issue.The same code runs smoothly using the Toplink provider


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jul 12, 2007 8:56 am 
Red Hat Associate
Red Hat Associate

Joined: Mon Aug 16, 2004 11:14 am
Posts: 253
Location: Raleigh, NC
No the problem is that you've specified that @Id is GENERATED by Hibernate. Do not set an ID before you save/persist it. That's the only problem here. Hibernate looks at the Entity you've passed in and assumes that because it has its PK populated that it is already in the database.

save() and persist() do almost the same things with slightly different semantics . persist() is JPA compliant and save() is a carryover from the original Hibernate. Mainly, save() returns the PK and persist() does not. However, both will generate the PK before the actual SQL INSERT happens (if the PK is generated and not assigned).

-Chris

_________________
Chris Bredesen
Senior Software Maintenance Engineer, JBoss


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jul 12, 2007 10:10 am 
Newbie

Joined: Wed May 30, 2007 4:45 am
Posts: 8
Location: Cape Town , South Africa
Hmmm , when i tried that persisting failed with "id cannot be null"


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jul 12, 2007 10:38 am 
Red Hat Associate
Red Hat Associate

Joined: Mon Aug 16, 2004 11:14 am
Posts: 253
Location: Raleigh, NC
Have you defined that ID column as an autoincrement? When I persist your bean to HSQL (having let Hibernate schema export create the schema) it works perfectly:

Code:
1456 DEBUG org.hibernate.SQL  - insert into USERS (ID, PASSWORD, USERNAME) values (null, ?, ?)
1461 DEBUG org.hibernate.type.StringType  - binding null to parameter: 1
1461 DEBUG org.hibernate.type.StringType  - binding 'foo' to parameter: 2
1462 DEBUG org.hibernate.SQL  - call identity()


-Chris

_________________
Chris Bredesen
Senior Software Maintenance Engineer, JBoss


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jan 23, 2009 12:33 pm 
Beginner
Beginner

Joined: Fri Jan 23, 2009 10:34 am
Posts: 25
Location: Switzerland
You might be interested by this post: How to avoid "detached entity passed to persist" exception


Top
 Profile  
 
 Post subject: Re: PersistentObjectException: detached entity passed to persist
PostPosted: Thu Nov 05, 2009 2:10 pm 
Newbie

Joined: Tue Nov 03, 2009 9:59 am
Posts: 5
Hi Chris,

I am having the same issue, here is my bean

@Entity
@Name("user")
@Scope(SESSION)
@Table(name="USER_DATA")
public class User implements Serializable{

private int id;
private String userName;
private String password;
private String forename;
private String surname;
private boolean enabled;
private Date dateOfBirth;
private String createdBy;
private Date createdDate;
private String modifiedBy;
private Date modifiedDate;
private String userEmail;
private Integer roleId;
private String verify;

//private Set<Role> roles;


public User(){}


@Id
@GeneratedValue
@Column(name="USER_ID")

@OneToOne(cascade = {CascadeType.REFRESH, CascadeType.REMOVE} , optional=false)
public int getId() {
return id;
}


here is my method from my action class

public String saveUser()
{

if (user.getPassword().equals(verify) )
{



List existing = em.createQuery(query)

.setParameter("username", user.getUserName())

.getResultList();

System.out.println(":::existing ::::>"+existing.size());

if (existing.size()==0)
{
System.out.println("<<:: ABOUT TO SAVE ::::>>>");


user.setCreatedBy(credentials.getUsername());
user.setCreatedDate(new java.util.Date());
em.persist(user);

pls see fraction of exception below

ERROR [application] javax.ejb.EJBTransactionRolledbackException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.taysay.drivetru.entity.User
javax.faces.el.EvaluationException: javax.ejb.EJBTransactionRolledbackException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.taysay.drivetru.entity.User
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

........


Caused by: javax.ejb.EJBTransactionRolledbackException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.taysay.drivetru.entity.User

..........



Pls I urgently need help

thanx plenti


Top
 Profile  
 
 Post subject: Re: PersistentObjectException: detached entity passed to persist
PostPosted: Thu Jun 26, 2014 6:39 am 
Newbie

Joined: Thu Jun 26, 2014 6:35 am
Posts: 1
Hi guys,

I remember having a similar issue, where the problem was that the primary key was defined as int/long instead of Integer/Long.

Maybe you can give that a try.

Cheers

Tom


Top
 Profile  
 
 Post subject: Re: PersistentObjectException: detached entity passed to persist
PostPosted: Fri Jul 25, 2014 5:06 am 
Newbie

Joined: Fri Jul 25, 2014 5:02 am
Posts: 1
Which means that you have done some mistake in the program I think so!!!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 12 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.