openxava / documentation / EJB3 JPA

Table of contents

Configure your application to work with EJB3
Using JPA in your code
Using JPA from a validator or a callback method
OpenXava supports EJB3 JPA since the version 2.1.

Configure your application to work with EJB3

Since v3.0 JPA is the default persistence engine, so you have to do nothing. But if you are using a v2.1 or v2.2 and you want to use JPA then edit the file properties/ of your project, and leave it in this way:
# EJB3 Java Persistence API
From now on, your application will use EJB3 JPA instead of Hibernate to manage object persistence.

Using JPA in your code

You can use the standard Java Persistence API in any part of an OpenXava application, that is, inside calculators, validators, actions, filters, etc.
In order to facilitate the use of JPA OpenXava provides the XPersistence class. For example, if you wish to store an object in a database using the JPA, the normal way would be:
EntityManagerFactory f = Persistence.createEntityManagerFactory("default");
EntityManager manager = f.createEntityManager();
Customer customer = ... ;
But, inside OpenXava and using XPersistence class you can write this:
Customer customer = ... ;
No more.
The first time that you call to XPersistence.getManager() a manager is created and assigned to the current thread and a transaction is created too; the next time that you call it, the same manager is used. At the end of the complete cycle of action execution, OpenXava commits automatically the transaction and closes the manager.
You can optionally commit the transaction in any moment calling to XPersistence.commit(), if after this you use XPersistence.getManager() an new manager and a new transaction are created for you.
You can learn more seeing the API doc of org.openxava.jpa.XPersistence class.

Using JPA from a validator or a callback method

Both validators and callback methods can be executed in flush time, so if you use XPersistence.getManager() from them it can produce problems. If you need to use JPA in your validator or callback method, you will need to open a separate entity manager by means of XPersistence.createManager() (so that JPA does not flush your ongoing create or update). Use code like the following to obtain and use a new EntityManager instance:
EntityManager em = XPersistence.createManager();
//... query logic
em.close(); // You have to close the manager
Also be aware of possible troubles with isolation levels and record locking when using this technique.