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="com.twinspires.cam"/>

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"
	  p:dataSource-ref="readWriteDataSource"
	  p:packagesToScan="com.javaninja.jpa"
	  p:jpaVendorAdapter-ref="jpaVendorAdapter"/>

<bean id="roEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
	  p:dataSource-ref="readOnlyDataSource"
	  p:packagesToScan="com.javaninja.jpa"
	  p:jpaVendorAdapter-ref="jpaVendorAdapter"/>

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

<jpa:repositories base-package="com.twinspires.cam" entity-manager-factory-ref="roEntityManagerFactory"/>
<jpa:repositories base-package="com.twinspires.cam" 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>
<bean id="roTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
	<property name="entityManagerFactory" ref="roEntityManagerFactory" />
	<qualifier value="ro"/>
</bean>

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 : XYZScripts.com