JPA Transactional Proxy for JavaSE

When using JPA in Java SE, it would still be helpful if a proxy would take care of the transactions and EntityManager life-cycle. I have created such a proxy for my Java/JPA and thought that perhaps others would like to use it as well.
Here is some client code using it

Foo f = JPAUtil.getTransactionalProxy(Foo.class);;

The bar method can then be implemented like this

public void bar(){
  EntityManager em = JPAUtil.getEntityManager();

The JPAUtil is used to create the proxy and to obtain the EntityManager. The proxy is created using javassist

It creates an JPA transactional proxy with following semantics:

  • Shares an EntityManager per thread
  • Opens and closes the entityManager for each method call
  • Transaction follow REQUIRED pattern (will join an existing transaction)
  • Uses the rollback only flag on the Transaction object
  • Rolls-back on «any» exception

This implementation does not inject the EntityManager into the target object

The whole code can be downloaded from github

Be Sociable, Share!
On November 3rd, 2011, posted in: Java by Tags: , ,