When to use entity manager flush in EJB 3.0

The flush API of entity manager is a very helpful operation as far as single transaction and CMP (Container Managed Persistence) is concerned. Especially when you are trying to save two related entities in a single transaction.


Lets say that we are trying to save a Student entity having a many-to-many relation with the Subject entity. Now, we are trying to add new Subject to a preexisting Student entity. Since, the Subject doesn’t exist in the db yet, and just to hit the nail on the head, lets also try and use the primary id of the new subject entity before ending the transaction. Seems impossible huh! Well, it isn’t.

Student student = getStudentByRollNo(rollNoVariable); 

// Create new subject 
Subject newSubject = new Subject(); 
// Populate subject except the primary id 

// Add new subject to a student 

// persist student object 
/* since the relation between the student and subject is many to many, when student 
is saved, the subject gets saved as well */ 

/* Here we are just dumping the entities in the context to the database */ 

newSubjectId = newSubject.getId(); 
/* Since the subject is now saved into the database, its ID is populated 
automatically */

This is where the flush method comes in handy. Another solution to this problem can be moving the logic to save the container entity into a separate transaction, basically a new transaction which is ensured by the REQUIRES_NEW annotation.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: