I am Siva, a passionate java developer, open source enthusiast, blogger. I like to cover Java, Struts, Spring, Hibernate, Ajax Tutorials, How-To's and Best Practices. Sivaprasadreddy is a DZone MVB and is not an employee of DZone and has posted 36 posts at DZone. You can read more from them at their website. View Full User Profile

Confusion Over Configuration

10.12.2012
| 7057 views |
  • submit to reddit
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).
 Everything seems to be working fine except one thing is missing, a smile on my face which usually I have when writing Spring code :-(. I like Spring framework very much and I am using it since 2006 and I enjoy working with Spring.  
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?    Anyway, with all the above excersise 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 :  http://www.sivalabs.in/2012/10/spring3jpa2javaee6appserver-confusion.html    
0
Published at DZone with permission of Sivaprasadreddy Katamreddy, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Junio Mousull replied on Mon, 2013/04/15 - 10:40pm

Spring aims to provide you a framework where there is "convention over configuration". However the reality is that Spring applications do need a certain amount of configuration. (Bloggou )

In the Spring 2.5.x and earlier versions, the common idiom was to provide this configuration via XML. With Spring 3.0+, the idiomatic way is to use annotations (something that Java EE6/7 also encourage).

As a side note, it can be amusing (saddening?) to see an annotated JPA entity, it's rather easy to add 4+ annotations to a single field....

Junio Mousull replied on Mon, 2013/04/15 - 10:43pm

On the other hand, it's also possible to have a JPA entity with a single @Entity annotation on the class and nothing else. If that isn't convention over configuration, I don't know what is. If you feel the need to have everything work exactly the way you want it, don't complain that  you end up with a lot of configuration - be glad that it's possible at all. Read more in roupas para revenda

Junio Mousull replied on Tue, 2013/04/16 - 9:22pm

 Exception saying "User is not mapped [from User]". JBoss is complaining that "Connection cannot be null when 'hibernate.dialect' not set" .... "[PersistenceUnit: Sivalabs1PU] Unable to build EntityManagerFactory". Tutorias in  dhea, lipo 6 unlimited and melatonina comprar

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.