How to bind the EntityManager in JNDI?

By default the persistence unit are available in the java: Context. If you wish to make them available also in the global naming Context you have to add two properties to your persistence.xml configuration file:

  1. jboss.entity.manager.jndi.name gives you a transaction scoped entity manager you can interact with
  2. jboss.entity.manager.factory.jndi.name binds the entity manager factory into global JNDI.
<persistence>
   <persistence-unit name="manager1">
      <jta-data-source>java:/MySQLDS</jta-data-source>
      <properties>
         <property name="jboss.entity.manager.jndi.name" value="java:/Manager1"/>
         <property name="jboss.entity.manager.factory.jndi.name" value="java:/Manager1Factory"/>
      </properties>
   </persistence-unit>
</persistence>

The typical use case for binding the EntityManager is to share the Persistence Unit across deployments. To achieve that:

  1. Firstly, the secondary deployment would declare a classloading dependency on the persistence jar deployment via jboss-deployment-structure.xml
  2. Then, just inject the EntityManager or look it up such as:
@Resource(lookup="java:/Manager1")
private EntityManager entityManager;

 

Found the article helpful? if so please follow us on Socials