Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to use GlassFish Managed JPA EntityManager in Spring

DZone's Guide to

How to use GlassFish Managed JPA EntityManager in Spring

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

When you deploy your application into a Java EE 5 application server it detects the persistence.xml, creates an EntityManager for each persistence unit, and exposes them in JNDI. You can get Spring to load the EntityManagers of all your persistence units from JNDI. First you need to tell web.xml that you want to load the persistence unit references from JNDI. The JNDI name always starts with "persistence/" and ends with the persistence unit name. For example:

 <persistence-unit-ref>  
<persistence-unit-ref-name>persistence/MyPU1</persistence-unit-ref-name>
<persistence-unit-name>MyPU1</persistence-unit-name>
</persistence-unit-ref>

<persistence-unit-ref>
<persistence-unit-ref-name>persistence/MyPU2</persistence-unit-ref-name>
<persistence-unit-name>MyPU2</persistence-unit-name>
</persistence-unit-ref>

 Next, add the following configuration to your Spring XML config file:

 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" >  
<property name="persistenceUnits">
<map>
<entry key="MyPU1" value="persistence/MyPU1"/>
<entry key="MyPU2" value="persistence/MyPU2"/>
</map>
</property>
</bean>

<tx:jta-transaction-manager/>
<tx:annotation-driven/>

Spring is now configured to use the JPA EntityManagers and JTA transactions from GlassFish. Use persistence.xml, @PersistenceUnit, and @PersistenceContext like normal. Use Spring's proprietary @Transactional annotation for transaction demarcation.  If you need to query both persistence units within the same transaction then you need to use XA data sources.

Originally posted on ryandelaplante.com

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}