Reading Java Persistence API spec #2
By Marina Vatkina on Aug 04, 2006
Today we'll look into the following sections of the spec and see how they can affect us in unexpected way:
3.1.1 EntityManager Interface
\* Clear the persistence context, causing all managed
\* entities to become detached. Changes made to entities that
\* have not been flushed to the database will not be
public void clear();
The semantics of the remove operation, applied to an entity X are as follows:
- If X is a new entity, it is ignored by the remove operation.
- If X is a detached entity, an IllegalArgumentException will be thrown by the remove
operation (or the transaction commit will fail).
Now let's look at the following code (which does not depend on whether it's executed in a Java EE or in a Java SE environment):
E e = new E(...);
System.out.println(em.contains(e)); // prints 'false'
This code will behave quite differently, depending on the actual steps in the method maybeCommitTransaction()!
If maybeCommitTransaction() is a no-op, entity 'e' actually becomes new again after clearing the persistence context, and it's ignored by the remove operation.
If maybeCommitTransaction() is a commit followed by a begin of a new transaction, entity 'e' becomes detached and remove will throw an IllegalArgumentException or commit will fail.
Note: em.contains(e) will return false in both cases.
If you are still confused, think about it in this way: a detached instance has a database state associated with it.