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.

Example:

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
newSubject.setName(“EJB3.0”);
// Add new subject to a student
student.getSubjects().add(newSubject);
// persist student object
entityManager.persist(student);
/* since the relation between the student and subject is many to many, when student
is saved, the subject gets saved as well */
entityManager.flush();
/* 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.