Figuring out the error: “Detached entity passed to persist”

Here’s a possible fix for this rather opaque error.

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist 

Regrettably there seems to be a lot of voodoo out there about fiddling with getters and setters, drawing pentagrams and such.

What helped me figure out the error was this stackoverflow answer.

“detached entity to persist exception will only occur when you are passing object which has primary key already set to persist ~ link to answer.”

The fix #

The problem for me was that I was trying to create new a project with a user object which had already been persisted to the database. That user object was in turn linked to another a user_role object through a @JoinTable. Furthermore, this chain of three entity objects had cascade.all set on their relations. When I then tried to save this complicated structure I ran into the detached entity exception. I then searched online and fiddled a lot with the cascading configurations and the like thinking the problem was there.

It turned out that I had so save the project object first. Afterwards I could then grab the user object from the database, do project.setUser(user) and save the project once more to create the necessary connection.

Hopefully this will actually help some of you out there and not add more needless voodoo. Let me know if this helped you.

Here is some further reading. In short, there is a lot of magic happening in the background when you have Spring JPA enabled repositories.

  1. How does Spring @Transactional Really Work?
  2. Spring Documenation: Transactions in-depth