Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Spring Data JPA is my favorite way to interact with the database in Java. It makes short work of defining queries. I get to spend my time on business logic instead of keeping the compiler happy. I didn’t know how to use Spring-Data-JPA when I have two entity managers. It boiled down to a couple of minor changes. Normally you would have to add the following to your XML to enable the repositories.

<jpa:repositories base-package=""/>

This doesn’t work because it can’t find the EntityManager named entityManager. That is because in my example, I have two entity managers. Here is how they are defined:

<bean id="rwEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"

<bean id="roEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"

This requires that I have two jpa:repositories entries like the following:

<jpa:repositories base-package="" entity-manager-factory-ref="roEntityManagerFactory"/>
<jpa:repositories base-package="" entity-manager-factory-ref="rwEntityManagerFactory"/>

Now that I have two entity managers wired up over the same packages and classes, I have another problem. I need to indicate via my code which entity manager I need to use for this call. I do this by adding @Transactional with the name of my transactionManager. As an extra note, when I declare my transaction manager and add the entity manager that it works on, I also add a qualifier for it. This creates an alias for that transaction manager. This allows me to note that the ro transaction manager works on this code instead of having to say the roTransactionManager works on this code. Here is the transaction manager declaration:

<bean id="rwtransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
	<property name="entityManagerFactory" ref="rwEntityManagerFactory" />
	<qualifier value="rw"/>
<bean id="roTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
	<property name="entityManagerFactory" ref="roEntityManagerFactory" />
	<qualifier value="ro"/>

This makes it easy to use the alias in my repository:

@Transactional(value = "ro")
Customer findByThisAndThat(String this, String that);

February 27th, 2016

Posted In: Java, java ninja, Javaninja, Spring, Spring Data, Spring Data JPA

Leave a Reply

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

LinkedIn Auto Publish Powered By :