Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code


Well, that was quick. It looks like there is now an easy way to do this. I don’t know if this is a Spring 4 feature, but I’m using Spring 4.2.4.

You can use @PersistenceContext to inject the LocalContainerEntityManagerFactoryBean directly.

@PersistenceContext(unitName = "entityManagerFactory")
private EntityManager entityManager;

NOTE: that the unitName was specified for the PersistenceContext. In this case, it is the id of the LocalContainerEntityManagerFactoryBean.

You don’t need the SharedEntityManagerBean



When working with Springframework, it is common to define an entity manager factory like the following.

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:dataSource-ref="mySqlDs" p:packagesToScan="" p:persistenceUnitName="persistenceUnit" p:jpaVendorAdapter-ref="jpaVendorAdapter">
	<property name="jpaProperties">
			<prop key="hibernate.show_sql">false</prop>
			<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

It is common for Data Access Objects (DAO) to inject the EntityManager via

@PersistenceContext(name = "entityManager")
private protected EntityManager entityManager;

In this case, injecting that way will not work because you don’t have an EntityManager. To create an EntityManager for your factory, use the SharedEntityManagerBean to do the following

<bean id="entityManager" class="">
	<property name="entityManagerFactory" ref="entityManagerFactory"/>

Now that you have an EntityManager, you can inject it via

@PersistenceContext(name = "entityManager")
private protected EntityManager entityManager;

The PersistenceContext annotation takes one of two properties.

  • name is used when an EntityManager is being specified
  • unitName is used when a PersistenceUnit name is being specified

January 23rd, 2016

Posted In: Java, java ninja, Javaninja, Spring

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By :