2

I was going through the JPA 2 specification and found two statements that sounds contradictory to me.

  1. "If X is a preexisting managed entity, it is ignored by the persist operation." - Pg 76

  2. "The EntityExistsException may thrown by the persistence provider when the persist operation is invoked and the entity already exists." - Pg 129

The statement 1 says something that sounds different from statement 2. So, my question is what is the difference between "preexisting managed entity" and "entity already exists"?

Community
  • 1
  • 1
Aceghn
  • 97
  • 8

1 Answers1

2

In version 2.1 of the spec, chapter 3.2.2, you can find this about the persist() operation:

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.
  • If X is a removed entity, it becomes managed.
  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time

So, persist() will ignore the entity if it's a managed object. It can throw an exception (or throw it, or another one, later) if the entity is a detached object.

First case:

Foo foo = em.find(Foo.class, 1L);
em.persist(foo); // ignored

Second case:

Foo foo = new Foo();
foo.setId(1L);
em.persist(foo); // may throw an exception
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • @ JB Nizet Please read the section on "Summary of Exceptions" in the Entity Operations chapter or check the below link on EntityExistsException; It says "Thrown by the persistence provider when EntityManager.persist(Object) is called and the entity already exists." http://docs.oracle.com/javaee/6/api/javax/persistence/EntityExistsException.html – Aceghn May 09 '15 at 17:00
  • @Aceghn That's an incomplete description of when the exception is thrown. The spec is the reference, and it clearly makes a difference between a detached entity and a managed one. – JB Nizet May 09 '15 at 17:02