About Siva Reddy

Katamreddy Siva Prasad is a Senior Software Engineer working in E-Commerce domain. His areas of interest include Object Oriented Design, SOLID Design principles, RESTful WebServices and OpenSource softwares including Spring, MyBatis and Jenkins.

Spring3 + JPA2 + Java EE6 App Server = 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 :-).

Reference: Spring3+JPA2+JavaEE6AppServer = Confusion Over Configuration from our JCG partner Siva Reddy at the My Experiments on Technology blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


9 + seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close