OSGi and JEE – Entity and transaction managers

Entity manager

In the previous post, the creation of EntityManagerFactory OSGi services from a persistence declaration file was discussed. An entity manager factory is however not the interface normally used in application programming. For that EntityManager instances are used.

An entity manager is the interface to perform persistence activities like retrieving and storing objects from the database. The OSGi enterprise specification does not mention it in the JPA chapter and that leaves a gap between the specification and the application programmer.

Looking at how an entity manager is used in JEE containers, which is via a @PersistenceContext annotated injection point, it is obvious to provide an OSGi entity manager service to application programmers so it can be injected into other beans via declarative services or service tracking. There are however two specific problems with this:

  1. According to the JEE specification, entity managers should only be used by one thread for the duration of a request. This cannot be guaranteed for normal OSGi services.
  2. In JEE, entity managers are managed by the container and closed at the end of a request. There is no such thing in OSGi.

The solution provided by the OSGi JEE extender project for issue 1. is to return a proxy for the entity manager OSGi service. This proxy will maintain an entity manager per thread and delegate the calls made through the proxy to that thread specific entity manager, see figure:

unnamed0This however still leaves issue 2. which is impossible to solve without an usage pattern. This pattern is via a JTA TransactionManager.

Transaction manager

The Java transaction API defines an interface for both application programmers as persistence implementers to cope with transactions. Application programmers normally use the UserTransaction interface while persistence implementers use the Transaction and TransactionManager APIs. In practice the user transaction is a simplified façade to the transaction manager API.

In the persistence implementation for the OSGi JEE extender project both are needed since interaction takes place with application programmers and persistence back-ends.

As such both a TransactionManager service as well as a UserTransaction service is provided by the JPA extender. The entity manager handling registers the constructed entity managers with the transaction manager to make sure that the constructed entity managers take part in the transaction and are closed on transaction end. From an application programmer point of view, transactions need to be started somewhere and ended elsewhere. This functionality is provided via an <codeUserTransaction OSGi service that is mainly an adapter to the transaction manager and transaction interfaces. Transactions