Excluding Entity from Spring JPA packagesToScan - spring

Is there a way to exclude an Entity in a package using Spring's LocalContainerEntityManagerFactoryBean and Hibernate? I am using spring-data if that matters. I would like to manage the excluded entity with another datasource. I know that you can do it using hibernateSessionFactory (Ignore some classes while scanning PackagesToScan), but I would prefer to use jpa if possible.
Here's my config:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">
<context:property-placeholder location="classpath:app.properties" ignore-unresolvable="true"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${class}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="packagesToScan">
<value>com.mypackage.new.entities</value>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
</props>
</property>
</bean>
<!-- Enables the Hibernate #Transactional programming model -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>

Related

JobRepositoryFactoryBean error spring batch

I started to learn spring batch and I have a problem that when i want to
persist the state of the job in a database using JobRepositoryFactoryBean.
compiler displays :
"Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in class path resource [springConfig.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/core/simple/ParameterizedRowMapper"
but not error when i use MapJobRepositoryFactoryBean
I'm using spring 5
springconfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="springbatch" />
<context:annotation-config />
<bean id="personneReaderCSV" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="input/personnes.txt" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="delimiter" value="," />
<property name="names" value="id,nom,prenom,civilite" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="targetType" value="springbatch.entities.Personne" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring_test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>springbatch.entities.Personne</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<job id="importPersonnes" xmlns="http://www.springframework.org/schema/batch">
<step id="readWritePersonne">
<tasklet>
<chunk reader="personneReaderCSV"
processor="personProcessor"
writer="personWriter"
commit-interval="2" />
</tasklet>
</step>
</job>
<bean id="daoPersonne" class="springbatch.dao.PersonneDaoImp">
<property name="factory" ref="sessionFactory"></property>
</bean>
<bean id="personWriter" class="springbatch.batch.PersonneWriter">
<property name="dao" ref="daoPersonne"></property>
</bean>
<bean id="personProcessor" class="springbatch.batch.PersonneProcess">
</bean>
<bean id="batchLauncher" class="springbatch.MyBean">
</bean>
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="Mysql" />
</bean>
<task:scheduled-tasks>
<task:scheduled ref="batchLauncher" method="message"
cron=" 59 * * * * * " />
</task:scheduled-tasks>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="org/springframework/batch/core/schema-drop-mysql.sql" />
<jdbc:script location="org/springframework/batch/core/schema-mysql.sql" />
</jdbc:initialize-database>
</beans>
but not error when i use :
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
You are using Spring Batch v2.2 with Spring Framework 5. That's not going to work properly as ParameterizedRowMapper has been removed in Spring Framework 4.2+ (hence the exception).
I recommend that you use Spring Batch v4.1 (since v2.x is not maintained anymore) and your issue should be fixed.
The best way to manage Spring dependencies is to let Spring Boot do it for you either by generating a project from start.spring.io or by using the Spring Boot BOM. With both ways, you will have the correct Spring projects dependencies that are known to work well together.

Spring #Transactional not committing records

I use Spring with Hibernate. I am using following configurations. When I try to save through Spring transaction, the record never commits.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<context:component-scan base-package="com.wpt.controllers,com.wpt.dao" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="wptDatasource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/wp" />
<property name="username" value="user" />
<property name="password" value="pass" />
</bean>
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="wptDatasource" />
<property name="packagesToScan" value="com.wpt.models" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="hibernate4AnnotatedSessionFactory">
</bean></beans>
MyControllerClass
#Transactional
#RequestMapping(...)
public String saveRecords(#ModelAttribute("orderObj") Order order){
for(Item item : order.getItems()){
itemDAO.save(item);
}
return "saveSuccess";
}
MyDAOClass
public void save(Item item){
session = sf.openSession();
session.save(item);
session.close();
}
The above #Transactional configuration not committing the record. But if I remove #Transactional from spring controller and use Hibernate transaction as below, the record commits.
public void save(Item item){
session = sf.openSession();
Transaction tx = session.beginTransaction();
session.persist(item);
tx.commit();
session.close();
}
This class commits the record.
I've gone through some forums and it's mentioned that #Transactional will take care of committing records. What mistake I am doing here? Can someone help?
Thanks in advance.
It worked after I have added <tx:annotation-driven /> annotation to my configuration xml & removed hibernate.current_session_context_class from hibernateSessionFactory bean. Given the changes below.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.wpt.controllers,com.wpt.dao" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="wptDatasource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/wp" />
<property name="username" value="user" />
<property name="password" value="pass" />
</bean>
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="wptDatasource" />
<property name="packagesToScan" value="com.wpt.models" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="hibernate4AnnotatedSessionFactory">
</bean>
</beans>
Then I have included org.springframework.transaction.annotation.Transactional annotation to all my service methods & removed all transactions from my DAO classes.
public void save(Item item){
//session = sf.openSession();
session.save(item);
//session.close();
}
Thanks all for your help.

Can i use ${<exp_string>} instead of #{<exp_string>} in SpEL in Spring 3.0.x?

I am using SpEL in my xml configuration file. By mistake i used ${} instead of #{}, but it is working. can i replace # with $ ?
Here is my code
config-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.balancesheetreconcile" />
<context:property-placeholder
location="classpath:database.properties classpath:mail-configuration.properties" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<mvc:annotation-driven />
<tx:annotation-driven proxy-target-class="true" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp">
</bean>
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="dd-MM-yyyy" />
</bean>
</constructor-arg>
<constructor-arg value="false" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref bean="dateEditor" />
</entry>
</map>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:username="${jdbc.username}"
p:password="${jdbc.password}" p:url="${jdbc.url}" />
<bean id="dataSourceSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.balancesheetreconcile.entities</value>
</list>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="dataSourceSessionFactory" />
<bean id="taskScheduler" class="com.balancesheetreconcile.utilities.TaskScheduler"
init-method="scheduleTask" />
<!-- Mail Sender bean -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${host}" />
<property name="port" value="${port}" />
<property name="username" value="${sender_username}" />
<property name="password" value="${sender_password}" />
<property name="javaMailProperties">
<props>
<prop key="${smtp_auth}">true</prop>
<prop key="${enable_ssl_tls}">true</prop>
<prop key="${mailing_protocol}">smtp</prop>
<prop key="${debug}">true</prop>
</props>
</property>
</bean>
</beans>
I am still confused regarding this. please help .Thanks in Advance
${...} are resolved by the properties placeholder from mail-configuration.properties.
That is entirely different to SpEL which evaluates expressions (usually not just simple properties) during context initialization.
For example #{someBean.foo} will get the value by calling getFoo() on someBean, and
#{SystemProperties['bar']} will use the value from the bar system property
(java ... -Dbar=baz).

TransactionRequiredException with WeblogicJtaTransactionManager

I am trying to work with distributed transactions in my application. For this purpose I have configured WeblogicJtaTransactionManager (provided by spring)to manage my distributed transaction. But its seems transactions are not starting. While running update query the get the following exception :
Executing an update/delete query; nested exception is
javax.persistence.TransactionRequiredException: Executing an update/delete query
My application context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.jasypt.org/schema/encryption http://www.jasypt.org/schema/encryption/jasypt-spring31-encryption-1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- <tx:jta-transaction-manager /> -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<context:component-scan base-package="com.myapp">
<context:exclude-filter type="regex" expression="com.myapp.controllers"/>
</context:component-scan>
<jee:jndi-lookup jndi-name="jdbc/myDataSource" id="dataSource"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jtaDataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="packagesToScan" value="com.myapp.domain" />
<property name="jpaProperties">
<props>
<prop key="javax.persistence.sharedCache.mode">NONE</prop>
<prop key="hibernate.dialect">${app.db.dailect}</prop>
<prop key="initialSize">${app.db.minpoolsize}</prop>
<prop key="maxActive">${app.db.maxpoolsize}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.max_fetch_depth">0</prop>
<prop key="hibernate.query.substitutions">true=1, false=0</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="javax.persistence.query.timeout">600000</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</prop>
<prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.WeblogicJtaPlatform</prop>
</props>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean> -->
<bean id="transactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager" >
<property name="transactionManagerName" value="javax.transaction.TransactionManager"/>
</bean>
<jpa:repositories base-package="com.myapp.repos" factory-class="com.myapp.repos.BaseRepositoryFactoryBean"
entity-manager-factory-ref="entityManagerFactory"/>
Any help is appreciated.
It is the problem with your datasource. You are using ComboPooledDataSource which is not managed by weblogic.

spring jpa hibernate with more datasources

I have to use two different database in my application(spring) with Hibernate,Jpa.
I'd like to define the different table directly to the different data sources.
So I use two different persistence unit and I try to use
<property name="packagesToScan" value="it.two.app.domain.first" />
and
<property name="packagesToScan" value="it.two.app.domain.second" />
putting the different tables into the different packages.
but It doesn't work.
Infact all the table is with the first data source.
then I tried to write into the perstistence XML file the name of the class
like
<persistence-unit name="persistenceFirst" transaction-type="RESOURCE_LOCAL">
<class>it.two.app.domain.first.OneTable</class>
<exclude-unlisted-classes/>
</persistence-unit>
and
it.two.app.domain.second.OtherTable
But when I run Log says
Table 'firstDB.other-table' doesn't exist
and I use into the services file
#PersistenceContext(unitName ="persistenceFirst")
private EntityManager em;
and
#PersistenceContext(unitName = "persistenceSecond")
EntityManager em;
Have you got some Ideas?
Thi is the data sources XML file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- first datasource -->
<context:property-placeholder location="classpath:jdbc-first.properties"/>
<bean id="dataSourceFirst" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<!-- second datasource -->
<context:property-placeholder location="classpath:jdbc-second.properties"/>
<bean id="dataSourceSecond" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="transactionManagerFirst" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="emfFirst"/>
<bean id="transactionManagerSecond" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="emfSecond"/>
<tx:annotation-driven transaction-manager="transactionManagerFirst"/>
<tx:annotation-driven transaction-manager="transactionManagerSecond"/>
<jpa:repositories base-package="it.two.app.repository.first"
entity-manager-factory-ref="emfFirst" transaction-manager-ref="transactionManagerFirst" />
<jpa:repositories base-package="it.two.app.repository.second"
entity-manager-factory-ref="emfSecond" transaction-manager-ref="transactionManagerSecond" />
<bean id="emfFirst"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceFirst"/>
<property name="persistenceXmlLocation" value="classpath:/META-INF/persistence-first.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="dataSource" ref="dataSourceFirst" />
<property name="packagesToScan" value="it.two.app.domain.first" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
</props>
</property>
</bean>
<bean id="emfSecond" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceSecond"/>
<property name="persistenceXmlLocation" value="classpath:/META-INF/persistence- second.xml"/>
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="dataSource" ref="dataSourceSecond"/>
<property name="packagesToScan" value="it.two.app.domain.second"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
</props>
</property>
</bean>
</beans>
SOLUTION!!!!!!
I undestand the problem.
Simply
<!-- first datasource -->
<bean id="dataSourceFirst" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="url...."
p:username="username" p:password="password" />
<!-- second datasource -->
<bean id="dataSourceSecond" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="url2...."
p:username="username2" p:password="password2" />
If you would like to use multiple DataSource in Spring + JPA.
Create two or more PersistenceUnit in persistence.xml.
Create EntityManagerFactory for each PersistenceUnit in spring-beans.xml.
More Reference.
Multiple database with Spring+Hibernate+JPA
Access Multiple Database Using Spring 3, Hibernate 3
Multiple Database using Spring 3.0 and Hibernate 3.0
In your DAO classes.
#PersistenceContext(unitName ="JPA_1")
private EntityManager em_1;
#PersistenceContext(unitName ="JPA_2")
private EntityManager em_2;
Conig persistence.xml
<persistence-unit name="JPA_1" type="RESOURCE_LOCAL">
....
</persistence-unit>
<persistence-unit name="JPA_2" type="RESOURCE_LOCAL">
....
</persistence-unit>
Config : spring-beans.xml
<bean id="entityManagerFactory1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JPA_1"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect"/> <--if it is necessary, replace with hibernate.
</property>
<property name="jpaPropertyMap">
<props>
<prop key="eclipselink.weaving">false</prop> <--if it is necessary, replace with hibernate.
</props>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
</bean>
</property>
</bean>
<bean id="entityManagerFactory2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JPA_2"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect"/> <--if it is necessary, replace with hibernate.
</property>
<property name="jpaPropertyMap">
<props>
<prop key="eclipselink.weaving">false</prop> <--if it is necessary, replace with hibernate.
</props>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
</bean>
</property>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"> <--if it is necessary, replace with hibernate.
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform"/>
<!--<property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform" />-->
<property name="generateDdl" value="false"/>
<property name="showSql" value="true"/>
</bean>

Resources