"detached entity passed to persist error" with JPA/EJB code

JavaJpaEjb 3.0

Java Problem Overview


I am trying to run this basic JPA/EJB code:

public static void main(String[] args){
		 UserBean user = new UserBean();
		 user.setId(1);
		 user.setUserName("name1");
		 user.setPassword("passwd1");
		 em.persist(user);
  }

I get this error:

javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.JPA.Database

Any ideas?

I search on the internet and the reason I found was:

> This was caused by how you created the objects, i.e. If you set the ID property explicitly. Removing ID assignment fixed it.

But I didn't get it, what will I have to modify to get the code working?

Java Solutions


Solution 1 - Java

The error occurs because the object's ID is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects. If persist concludes the object is detached (which it will because the ID is set), it will return the "detached object passed to persist" error. You can find more details here and here.

However, this only applies if you have specified the primary key to be auto-generated: if the field is configured to always be set manually, then your code works.

Solution 2 - Java

ERD

Let's say you have two entities Album and Photo. Album contains many photos, so it's a one to many relationship.

Album class

@Entity
public class Album {
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	Integer albumId;
	
	String albumName;
	
	@OneToMany(targetEntity=Photo.class,mappedBy="album",cascade={CascadeType.ALL},orphanRemoval=true)
	Set<Photo> photos = new HashSet<Photo>();
}

Photo class

@Entity
public class Photo{
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	Integer photo_id;

	String photoName;

	@ManyToOne(targetEntity=Album.class)
	@JoinColumn(name="album_id")
	Album album;
	
}

What you have to do before persist or merge is to set the Album reference in each photos.

		Album myAlbum = new Album();
		Photo photo1 = new Photo();
		Photo photo2 = new Photo();
		
		photo1.setAlbum(myAlbum);
		photo2.setAlbum(myAlbum);		
                    

That is how to attach the related entity before you persist or merge.

Solution 3 - Java

remove

user.setId(1);

because it is auto generate on the DB, and continue with persist command.

Solution 4 - Java

I got the answer, I was using:

em.persist(user);

I used merge in place of persist:

em.merge(user);

But no idea, why persist didn't work. :(

Solution 5 - Java

if you use to generate the id = GenerationType.AUTO strategy in your entity.

Replaces user.setId (1) by user.setId (null), and the problem is solved.

Solution 6 - Java

Here .persist() only will insert the record.If we use .merge() it will check is there any record exist with the current ID, If it exists, it will update otherwise it will insert a new record.

Solution 7 - Java

I know its kind of too late and proly every one got the answer. But little bit more to add to this: when GenerateType is set, persist() on an object is expected to get an id generated.

If there is a value set to the Id by user already, hibernate treats it as saved record and so it is treated as detached.

if the id is null - in this situation a null pointer exception is raised when the type is AUTO or IDENTITY etc unless the id is generated from a table or a sequece etc.

design: this happens when the table has a bean property as primary key. GenerateType must be set only when an id is autogenerated. remove this and the insert should work with the user specified id. (it is a bad design to have a property mapped to primary key field)

Solution 8 - Java

If you set id in your database to be primary key and autoincrement, then this line of code is wrong:

user.setId(1);

Try with this:

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

Solution 9 - Java

I had this problem and it was caused by the second level cache:

  1. I persisted an entity using hibernate
  2. Then I deleted the row created from a separate process that didn't interact with the second level cache
  3. I persisted another entity with the same identifier (my identifier values are not auto-generated)

Hence, because the cache wasn't invalidated, hibernate assumed that it was dealing with a detached instance of the same entity.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzengrView Question on Stackoverflow
Solution 1 - JavaTomislav Nakic-AlfirevicView Answer on Stackoverflow
Solution 2 - JavazawhtutView Answer on Stackoverflow
Solution 3 - JavaAmmar BozorgvarView Answer on Stackoverflow
Solution 4 - JavazengrView Answer on Stackoverflow
Solution 5 - JavaSergio OrdóñezView Answer on Stackoverflow
Solution 6 - JavaPSRView Answer on Stackoverflow
Solution 7 - JavaharipriyaView Answer on Stackoverflow
Solution 8 - JavaNemusView Answer on Stackoverflow
Solution 9 - JavahertzsprungView Answer on Stackoverflow