Reading Java Persistence API spec #2

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
\* persisted.
\*/
public void clear();

3.2.2 Removal


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):


startTransaction();

E e = new E(...);
em.persist(e);

maybeCommitTransaction();

em.clear();
System.out.println(em.contains(e));
// prints 'false'

em.remove(e);

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.

Comments:

Post a Comment:
Comments are closed for this entry.
About

Marina Vatkina

Search

Top Tags
Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
News

No bookmarks in folder

Blogroll
Related Links