The Java EE tutorial states:
...
[i][b]Synchronizing Entity Data to the Database[/b]
The state of persistent entities is synchronized to the database when the transaction with which the entity is associated commits. If a managed entity is in a bidirectional relationship with another managed entity, the data will be persisted based on the owning side of the relationship.
To force synchronization of the managed entity to the data store, invoke the flush method of the entity. If the entity is related to another entity, and the relationship annotation has the cascade element set to PERSIST or ALL, the related entity’s data will be synchronized with the data store when flush is called.[/i]
...
According to the preceding excerpt any changes to a simple entity should be persisted
when the transaction commits and no 'flush' is required.
I've written a simple servlet based on the bookstore example from the same tutorial.
My servlet class:
public class RegistrationServlet extends HttpServlet {
@Resource
protected UserTransaction utx;
...
public synchronized void addUser(String email, String password) throws Exception {
try {
utx.begin();
this.db.addUser(email, password);
utx.commit();
} catch (Exception ex) {
utx.rollback();
throw ex;
}
}
...
[i]this.db[/i] is a database object created via ContexListener:
public class DB {
@Resource
private EntityManager em;
...
public void addUser(String email, String password) {
User u = new User(email, password);
em.persist(u);
em.flush(); //no data is inserted into the database without this line
}
...
[i]User[/i] is an entity class. When I remove the [i]em.flush()[/i] from
the code above no insert is done even though the transaction
in the [i]RegistrationServlet[/i] commits.
My [i]User[/i] entity class is a stand alone entity that has no relations
to any other entities in the project. It should be inserted into my
database without the need to call [i]em.flush()[/i].
Why is the [i]em.flush()[/i] necessary in this case?
JavaDB, Glassfish 2.1, Netbeans 6.7.
[Message sent by forum member 'dziku' (dziku)]
http://forums.java.net/jive/thread.jspa?messageID=355560