Skip to content
Advertisement

How to detach an entity from an EntityManager

My environment

Java 7/JPA 2/Hibernate 5.1.

My Scenario

I’m building a Repository pattern implementation. All code is written and it all works fine when no error condition happens.

However, let’s say that three entity instances are added to the repository. First and third are ok, but second lacks value for a mandatory (not null) column. A DB error will be returned when the repository is saved.

When facing this condition a batch process should just write a log message somewhere, skip the invalid object and continue to the others. In order to do that, this invalid entity should only be removed from the repository, what means to detach it from the underlying EntityManager this repository uses.

My problem

The repository.exclude(entity) method call (that internally detaches the entity from the EntityManager) seems to not be working and a second attempt to save the repository fails again.

My (partial) AbstractRepository class

JavaScript

My Repository declaration

JavaScript

My test code

JavaScript

My persistence.xml

JavaScript

The save() method updated

Here is a new version of the save() method that makes things work. It was needed to call flush() before commit() and no more persist() for those entities that did not create any problem, but merge() them, since they already have an Id.

JavaScript

Advertisement

Answer

Converting an comment to an answer:

According to this guide, you need to flush() before detaching the entity

Update code from OP:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement