Doing EJB-like transactions with Google App Engine

Using Google App Engine you can’t define a method as transactional with a simple annotation as you can in EJB.
You always need to call some boilerplate code which gets quite annoying.
Therefore the following utility class comes handy, which takes care of the transaction handling for you:

To make use of it, you have to set the same persistence unit as in your persistence.xml configuration file first. Do this by changing the parameter of the method createEntityManagerFactory.

After that you can easily define transcation boundaries like this:

In this example the transaction method has a return type of String – change this if you need a different one.
The transaction is always starting a new transaction, similar to REQUIRES_NEW in EJB (more about that in the Java EE 6 tutorial). If you want to use another transaction strategy, you will have to modify the code.
It is still not as easy as setting an annotation in EJB, but way better than without. If you want to define transactions for Google App Engine via annotations, you will need some DI engine like Guice or CDI, but then you add a lot of other code that you probably don’t need.