Friday, October 12, 2012

Spring3+JPA2+JavaEE6AppServer = Confusion Over Configuration

Spring is great, JavaEE6 is great and latest JavaEE6 Application servers are also great. This post is not a rant on Spring Vs JavaEE6, but my experience of porting a Spring3+JPA2(Hibernate) application on JBoss AS-7.1 App Server.

My application requirement is very simple: Developing a couple of SOAP based webservices using Spring3.1 and JPA2(Hibernate) and host it on JBoss AS 7.1.

So I started creating a multi-module maven project with one jar module containing the service implementations using Spring & JPA and another war module which exposes those services as SOAP based webservices. But the key part is services needs to talk to multiple databases for some of the service methods.

 I am aware of JPA2 integration support from Spring without persistence.xml and cool packagesToScan attribute which makes life a bit easier. I configured 2 dataSources, 2 LocalContainerEntityManagerFactoryBeans, registered 2 JpaTransactionManagers and enabled Annotation based Transaction Management Support.


	<tx:annotation-driven transaction-manager="txnManager1"/>
	<tx:annotation-driven transaction-manager="txnManager2"/>
	
	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/><!-- This will throw error because it found multiple EntityManagerFactory beans -->
	
	<bean id="txnManager1" 
			class="org.springframework.orm.jpa.JpaTransactionManager"
       		p:entityManagerFactory-ref="emf1"/>
    
    <bean id="txnManager2" 
			class="org.springframework.orm.jpa.JpaTransactionManager"
       		p:entityManagerFactory-ref="emf2"/>       		
       
    <bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       	<property name="persistenceUnitName" value="Sivalabs1PU"></property>       	
       	<property name="dataSource" ref="dataSource1"></property>
       	<property name="jpaVendorAdapter">
       		<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
         			p:showSql="${hibernate.show_sql}"/>
       	</property>
       	<property name="jpaProperties">
       		<props>
       			<prop key="hibernate.dialect">${hibernate.dialect}</prop>
       			<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
       		</props>
       	</property>
       	<property name="packagesToScan" value="com.sivalabs.springdemo.entities"></property>
       	<property name="loadTimeWeaver">
          <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
        
    </bean> 
    
   	<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       	<property name="persistenceUnitName" value="Sivalabs2PU"></property>
       	<property name="dataSource" ref="dataSource2"></property>
       	<property name="jpaVendorAdapter">
       		<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
         			p:showSql="${hibernate.show_sql}"/>
       	</property>
       	<property name="jpaProperties">
       		<props>
       			<prop key="hibernate.dialect">${hibernate.dialect}</prop>
       			<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
       		</props>
       	</property>
       	<property name="packagesToScan" value="com.sivalabs.springdemo.entities"></property>
       	<property name="loadTimeWeaver">
          <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
        
    </bean> 
	
	<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${node1.jdbc.driverClassName}"></property>
		<property name="url" value="${node1.jdbc.url}"></property>
		<property name="username" value="${node1.jdbc.username}"></property>
		<property name="password" value="${node1.jdbc.password}"></property>
	</bean>
	
	<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${node2.jdbc.driverClassName}"></property>
		<property name="url" value="${node2.jdbc.url}"></property>
		<property name="username" value="${node2.jdbc.username}"></property>
		<property name="password" value="${node2.jdbc.password}"></property>
	</bean>

After this I realized to bind Entitymanager with the correct PersistenceUnit I need to give persistenceUnitName to LocalContainerEntityManagerFactoryBean.

	
	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
		<property name="persistenceUnits" >
	     <map>
	       <entry key="unit1" value="Sivalabs1PU"/>
	       <entry key="unit2" value="Sivalabs2PU"/>
	     </map>
		</property>
	</bean>
	
	<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       	<property name="persistenceUnitName" value="Sivalabs1PU"></property>
       	<property name="dataSource" ref="dataSource1"></property>
       	....
		....        
    </bean> 
    
   	<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       	<property name="persistenceUnitName" value="Sivalabs2PU"></property>
       	<property name="dataSource" ref="dataSource2"></property>
        ....
		....        
    </bean>

Then in my Service Bean EntityManagers and transaction managers are glued together as follows:

@Service
public class AdminUserService implements UserService
{
	@PersistenceContext(unitName="Sivalabs1PU")
	private EntityManager sivalabs1EM;
	@PersistenceContext(unitName="Sivalabs2PU")
	private EntityManager sivalabs2EM;
	
	@Override
	@Transactional("txnManager1")
	public List<User> getAllUsersFromSivalabs1DB() {
		return sivalabs1EM.createQuery("from User", User.class).getResultList();
	}

	@Override
	@Transactional("txnManager2")
	public List<User> getAllUsersFromSivalabs2DB() {
		return sivalabs2EM.createQuery("from User", User.class).getResultList();
	}
	
}

With this setup now I got the Exception saying "No persistence unit with name 'Sivalabs1PU' found".

Then after some googling I created  META-INF/persistence.xml file as follows:



<persistence>

   <persistence-unit name="Sivalabs1PU" transaction-type="RESOURCE_LOCAL">   		
   </persistence-unit>
   
   <persistence-unit name="Sivalabs2PU"  transaction-type="RESOURCE_LOCAL">   		
   </persistence-unit>
   
</persistence>

Now the persistence unit name error got resolved and got other Exception saying "User is not mapped [from User]". The User class is annotated with @Entity and is in "com.sivalabs.springdemo.entities" package which I configured to "packagesToScan" attribute. I didn't understand why "packagesToScan" attribute is not working which is working fine without persistence.xml. So for time being I configured entity classes in persistence.xml file.

<persistence>

   <persistence-unit name="Sivalabs1PU" transaction-type="RESOURCE_LOCAL">   	
		<class>com.sivalabs.springdemo.entities.User</class>   
   </persistence-unit>
   
   <persistence-unit name="Sivalabs2PU"  transaction-type="RESOURCE_LOCAL">   	
		<class>com.sivalabs.springdemo.entities.User</class>
   </persistence-unit>
   
</persistence>

Finally when I ran my JUnit Test which invokes AdminUserService methods everything looks good and working fine. Then I deployed the war file on JBoss AS 7.1 Server then again got a bunch of errors. JBoss is complaining that "Connection cannot be null when 'hibernate.dialect' not set" .... "[PersistenceUnit: Sivalabs1PU] Unable to build EntityManagerFactory".

After thinking for a couple of minutes, I understood that JBoss server is trying to do what it is supposed to do with "Convention Over Configuration" rules. JBoss is trying to create EntityManagerFactory because it found META-INF/persistence.xml in classpath. But as it doesn't contain jdbc connection details its throwing Error. 

Again after some googling I found we can rename persistence.xml to something else(spring-persistence.xml) and hook up this new name with Spring as follows:

	<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       	<property name="persistenceUnitName" value="Sivalabs1PU"></property>
		<property name="persistenceXmlLocation" value="classpath:META-INF/spring-persistence.xml"/>
       	<property name="dataSource" ref="dataSource1"></property>
       	....
		....        
    </bean> 
    
   	<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       	<property name="persistenceUnitName" value="Sivalabs2PU"></property>
		<property name="persistenceXmlLocation" value="classpath:META-INF/spring-persistence.xml"/>
       	<property name="dataSource" ref="dataSource2"></property>
        ....
		....        
    </bean>

Finally I got this application working on my JBoss AS 7.1 successfully(Still I don't know how many other holes are there that I haven't yet found).

But here I didn't understand few Spring concepts:
1. When I try to give persistenceUnitName why Spring is checking for that name to be existed in persistence.xml? Anyway that persistence.xml doesn't contain anything exception the unit-name!!

2. Why packagesToScan mechanism is failing when used with persistence.xml? Is it a Spring Bug?

Everything seems to be working fine except one thing is missing, a smile on my face which usually I have when working with Spring and Tomcat :-(

I like Spring framework very much and I am using it since 2006 and I do enjoy while writing Spring code. That doesn't mean I don't like CDI, EJB3, JAX-RS :-)

 Anyway, with all the above exercise I feel like Spring3+JPA2+JavaEE6AppServer=Confusion Over Configuration and it is my(an average java developer) opinion only.

Again say one more time : Spring is great, JavaEE6 is great and latest JavaEE6 Application servers are also great :-).

3 comments:

  1. FYI - new Spring 3.1 feature allows to completely abstain from creating a persistence.
    xml file to declare the entity classes. Instead, you can use Spring’s classpath scanning
    feature through the packagesToScan property of the LocalContainerEntityManagerFac
    toryBean. This will trigger Spring to scan for classes annotated with @Entity and @Map
    pedSuperclass and automatically add those to the JPA PersistenceUnit

    ReplyDelete
    Replies
    1. Hi,
      I am aware of packagesToScan attribute and in fact I mentioned about it in the post. Please try to create multiple EntityManagerFactories as described in the article and you will realize the problem.

      Delete
  2. Dear Friends.I am working on multi module project where i need to use only single Localcontainerentitymanagerfactory .But i am implemented by each module has separate entity with correponding repositories.It seems i need to use multiple local containermanager factory for scanning the repository.how to do with single localcontainer entitymanager factory with single data source.Please help me out.please post your answers to this mail id mailtofeescorner@gmail.com

    ReplyDelete