Tuesday, December 31, 2013

I'm trying to configure Spring+Hibernate+JPA for work with two databases (MySQL and MSSQL)
my datasource-context.xml:
xml version="1.0" encoding="UTF-8"?>
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:util="http://www.springframework.org/schema/util">

 
  id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}"
  p:username="${local.jdbc.username}" p:password="${local.jdbc.password}">
 

  id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close" p:driverClassName="${remote.jdbc.driver}"
  p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}"
  p:password="${remote.jdbc.password}" />

  id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
  p:entity-manager-factory-ref="entityManagerFactory" />

 
  transaction-manager="transactionManager" />

  id="persistenceUnitManager"
  class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
         name="persistenceXmlLocations">
    value-type="java.lang.String">
    classpath*:config/persistence.local.xml
classpath*:config/persistence.remote.xml name="dataSources"> key="localDataSource" value-ref="dataSource" /> key="remoteDataSource" value-ref="dataSourceRemote" /> name="defaultDataSource" ref="dataSource" /> id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> name="jpaVendorAdapter"> class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> name="persistenceUnitManager" ref="persistenceUnitManager" /> name="persistenceUnitName" value="localjpa"/> class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
each persistence.xml contains one unit, like this:
 name="remote" transaction-type="RESOURCE_LOCAL">
  
    name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
    name="hibernate.dialect" value="${remote.hibernate.dialect}" />
    name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" />
  
PersistenceUnitManager cause following exception:
Cannot resolve reference to bean 'persistenceUnitManager' while setting bean property 'persistenceUnitManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [config/datasource-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation': no matching editors or conversion strategy found
If left only one persistence.xml without list, every works fine but I need 2 units...
I also try to find alternative solution for work with two databases in Spring+Hibernate context, so I would appreciate any solution
new error after changing to persistenceXmlLocations
No single default persistence unit defined in {classpath:config/persistence.local.xml, classpath:config/persistence.remote.xml}
UPDATE: I add persistenceUnitName, it works, but only with one unit, still need help
UPDATE: thanks, ChssPly76
I changed config files: datasource-context.xml
xml version="1.0" encoding="UTF-8"?>
 xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util">

     id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}"
     p:username="${local.jdbc.username}" p:password="${local.jdbc.password}">
    

     id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close" p:driverClassName="${remote.jdbc.driver}"
     p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}"
     p:password="${remote.jdbc.password}">
    

    
     class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
      name="defaultPersistenceUnitName" value="pu1" />
    

     id="persistenceUnitManager"
     class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
      name="persistenceXmlLocation" value="${persistence.xml.location}" />
      name="defaultDataSource" ref="dataSource" /> 
      name="dataSources">
      
        key="local" value-ref="dataSource" />
        key="remote" value-ref="dataSourceRemote" />
      
id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> name="jpaVendorAdapter"> class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> name="persistenceUnitManager" ref="persistenceUnitManager" /> name="persistenceUnitName" value="pu1" /> name="dataSource" ref="dataSource" /> id="entityManagerFactoryRemote" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> name="jpaVendorAdapter"> class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> name="persistenceUnitManager" ref="persistenceUnitManager" /> name="persistenceUnitName" value="pu2" /> name="dataSource" ref="dataSourceRemote" /> /> id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactory" /> id="transactionManagerRemote" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactoryRemote" />
persistence.xml
xml version="1.0" encoding="UTF-8"?>
 xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

     name="pu1" transaction-type="RESOURCE_LOCAL">
     
       name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
       name="hibernate.dialect" value="${local.hibernate.dialect}" />
       name="hibernate.hbm2ddl.auto" value="${local.hibernate.hbm2ddl.auto}" />          
     
name="pu2" transaction-type="RESOURCE_LOCAL"> name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> name="hibernate.dialect" value="${remote.hibernate.dialect}" /> name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" />
Now it builds two entityManagerFactory, but both are for Microsoft SQL Server [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: pu1 ...] [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server
[main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: pu2 ...] [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server (but must MySQL)
I suggest, that use only dataSource, dataSourceRemote (no substitution) is not worked. That's my last problem
share|improve this question
add comment

4 Answers

You need to use persistenceXmlLocations property (note the plural) rather thanpersistenceXmlLocation. It's a string array, so it'll be auto-converted from list:
 id="persistenceUnitManager"
      class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
   name="persistenceXmlLocations">
    classpath*:config/persistence.local.xml
classpath*:config/persistence.remote.xml ...
Update (based on edit)
Your entityManagerFactory does not specify persistenceUnitName property. You have to do so explicitly because you're defining more than one persistence unit and entityManagerFactory has to know which one to use.
share|improve this answer
 
:) thanks, you are right, but now I have new error –  ziftech Dec 14 '09 at 21:57
 
If it's related to this one, perhaps you can update your question and I'll take a look. If it's not directly related it's probably better to post a new question. –  ChssPly76 Dec 14 '09 at 22:00
1 
ok, so if I set persistenceUnitName explicitly, it will works, but only with one unit. How can I switch units in application? –  ziftech Dec 15 '09 at 7:25
 
You can't "switch" them. You can, however, create more than one entityManagerFactory instance - one per persistence unit. You can then specify unitName on PersistenceContext annotation in your code to choose which factory will produce the entity manager that will get injected. –  ChssPly76 Dec 15 '09 at 16:32
 
hi all, i read the code above, so it is legal to created more than one org.springframework.orm.jpa.JpaTransactionManager and use @transactional("name") ? –  cometta Dec 26 '09 at 3:33
add comment
Justin, number 3 can be done in a more standard way like this:
  1. In your Spring context:
     />
  2. In your Spring-managed DAOs (note the unitName property):
    @PersistenceContext(unitName = "pu1"`) protected EntityManager entityManager;
This way a properly intantiated EntityManager corresponding to the persistence unit named "pu1" would be injected in the corresponding DAOs.
share|improve this answer
 
I don't believe that Spring supports the unitName attribute prior to version 3, FYI. –  Lyle Jan 31 '11 at 21:00
add comment
If you follow this tutorial, http://www.javacodegeeks.com/2010/05/jboss-42x-spring-3-jpa-hibernate.htmlyou can make the following changes to access two different databases:
  1. persistence.xml, define a second pesristence-unit for your second database.
  2. spring.xml, define a second entityManagerFactory bean under a different name, lets say "entityManagerFactoryDB2" and configure it to use the persistent unit for the second database.
  3. for every DAO you want to access the second database include the following :
    @Autowired
    private EntityManagerFactory entityManagerFactoryDB2;
    
    @PostConstruct
    public void init() {
        super.setEntityManagerFactory(entityManagerFactoryDB2);
    }
Thats all!
On spring service classes, use the DAOs as usual!
share|improve this answer
add comment

7 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Anna said...

Great and Useful Article.

Online Java Training

Online Java Course

Java EE course

Java Course in Chennai

Java Training in Chennai

Java Training Institutes in Chennai

Java Interview Questions

Java Interview Questions

Zheng junxai5 said...


zhengjx20160721
adidas superstar shoes
supra footwear
jordan concords
christian louboutin shoes
longchamp le pliage
rolex watches
fit flops
coach outlet store online clearances
celine bags
ray ban sunglasses outlet
kate spade outlet
oakley outlet
louis vuitton outlet online
louis vuitton
ray ban sunglasses outlet
toms shoes
replica rolex watches
michael kors outlet clearance
jordan retro 4
kobe 8
coach factory outlet online
rolex watches
nike free uk
coach factory outlet
air max
kate spade handbags
louis vuitton outlet stores
cheap ray ban sunglasses
kd 8
ralph lauren polo
air jordan 4
jordan 6s
air jordan homme
michael kors outlet clearance
rolex watches
louis vuitton handbags
designer handbags
coach outlet online
cheap basketball shoes
oakley canada

raybanoutlet001 said...

cheap air jordan
michael kors handbags
adidas stan smith
michael kors uk
adidas stan smith men
fitflops sale
cheap nfl jerseys
christian louboutin shoes
nike air huarache
discount oakley sunglasses
huarache shoes
cheap basketball shoes
nike zoom
oakley sunglasses
http://www.oakley-sunglass.in.net
tiffany online
jordan shoes on sale
adidas nmd for sale
nike air zoom structure 19
yeezy shoes
air jordans,cheap air jordans,air jordan shoes,air jordan 11,air jordan 13,air jordan 6,air jordan 4