Error when setting 2 DataBases without bean annotation using SpringData - spring

I have problem when i try configure 2 dataSources in my xml applicationContext.xml.
The examples i find reffer using bean annotation for configuration.
i need configuration in xml in my actual architecture.
I saw tutorial:
http://www.baeldung.com/spring-data-jpa-multiple-databases
and
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
But i don't solve my problem, the method used in this Spring page use annotation. I can't use annotation, my configuration is there in xml.
When i try apply seconf datasource has error.
Before add second datasource, work's fine!
When add second datasource don't work.
My applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
default-autowire="byName" default-lazy-init="true">
<context:annotation-config />
<context:component-scan base-package="br.com.myProject" />
<jpa:repositories base-package="br.com.myProject.ged.repository"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:jboss/datasources/sgedDS" />
<property name="resourceRef" value="true" />
</bean>
<bean id="dataSourceNurer" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:jboss/datasources/nurerDS" />
<property name="resourceRef" value="true" />
</bean>
<!-- ************** ENTITY MANAGER SGED ******************** -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="br.com.myProject.ged.entity" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>
<!-- ************** ENTITY NURER NURER ******************** -->
<bean id="entityManagerFactoryNurer" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="br.com.myProject.ged.entity" />
<property name="dataSource" ref="dataSourceNurer" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>
<!-- ******** SGED ******** -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- ******** NURER ******** -->
<bean id="transactionManagerNurer" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryNurer" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" /> <!-- SGED -->
<tx:annotation-driven transaction-manager="transactionManagerNurer" /> <!-- NURER -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="br.com.myProject.ged.spring.SpringViewScope" />
</entry>
</map>
</property>
</bean>
</beans>
My Bean Service layer:
#Transactional (transactionManager = "transactionManager2")
public List<DataBase2Entity> getAll(){
return nurerSituacaoIdrRepository.findAll();
// return new ArrayList<DataBase2Entity>();
}
#Transactional (transactionManager = "transactionManager")
public List<DataBaseEntity> getAll(){
return nurerSituacaoIdrRepository.findAll();
// return new ArrayList<DataBaseEntity>();
}
My BaseDao.java
public abstract class BaseDao<T> {
private Class<T> entityClass;
#PersistenceContext(unitName = "entityManagerFactory")
private EntityManager em;
#PersistenceContext(unitName = "entityManagerFactoryNurer")
private EntityManager emNurer;
#SuppressWarnings("unchecked")
public BaseDao() {
this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
...
UPDATE : 02/10/2017
ERROR execution time:
Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Error setting property values
I use same entityManagerFactory or create another entityManagerFactory (see BaseDao.java).

This seems to be an issue with XML.
I see there is a . (dot) at the end on line no #105
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>.
Remove the dot and try again.

Related

Hazelcast client spring configuration

I have createed a Hazelcast manager which uses spring, hibernate, jpa. I can start my hazelcast instance.
The problem I have is I dont know how to configure a hazelcast client using spring config. I want to use in some other server component a hazelcast-client
I really have no idea how to start
any help would be appreciated
Below is my spring config for hazelcast server
Johan
<?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:hz="http://www.hazelcast.com/schema/spring"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.hazelcast.com/schema/spring
http://www.hazelcast.com/schema/spring/hazelcast-spring.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${ecs.config.path}/ecs.properties</value>
<value>classpath*:config/ecs.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true" />
</bean>
<context:component-scan base-package="nl.ict.psa.ecs.hazelcast.dao,nl.ict.psa.ecs.hazelcast.mapstores,nl.ict.psa.ecs.hazelcast.service" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${datasource.driverClassName}" />
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.username}"/>
<property name="password" value="${datasource.password}"/>
</bean>
<bean id="hazelcast" class="com.hazelcast.core.Hazelcast"/>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="PU" />
<property name="packagesToScan">
<list>
<value>nl.ict.psa.hazelcast.model.ecs</value>
<value>nl.ict.psa.hazelcast.model.ecs.ocr</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.archive.autodetection">class</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<bean id="transpInfo" class="nl.ict.psa.ecs.hazelcast.mapstores.TranspInfoMapStore"/>
<hz:hazelcast id="instance">
<hz:config>
<hz:network port="5701" port-auto-increment="true">
<hz:join>
<hz:multicast enabled="false"/>
</hz:join>
</hz:network>
<hz:map name="transp" read-backup-data="true">
<hz:map-store enabled="true" write-delay-seconds="60"
initial-mode="LAZY"
implementation="transpInfo"/>
</hz:map>
</hz:config>
</hz:hazelcast>
</beans>
Configured Multiple Ip's Using Pragmatically.
#Bean
public ClientConfig clientConfig() {
ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig();
networkConfig.addAddress("172.17.0.4:5701", "172.17.0.6:5701")
.setSmartRouting(true)
.addOutboundPortDefinition("34700-34710")
.setRedoOperation(true)
.setConnectionTimeout(5000)
.setConnectionAttemptLimit(5);
return clientConfig;
}
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
I would suggest to must read. http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#configuring-client-connection-strategy
Something like this (from https://github.com/neilstevenson/spring-boot-autoconfigure-test/tree/master/hazelcast-imdg-client)
#Configuration
#ConditionalOnMissingBean(ClientConfig.class)
static class HazelcastClientConfigConfiguration {
#Bean
public ClientConfig clientConfig() throws Exception {
return new XmlClientConfigBuilder().build();
}
}
#Configuration
#ConditionalOnMissingBean(HazelcastInstance.class)
static class HazelcastClientConfiguration {
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
}
Try to avoid XML, Spring is moving away from it.

Spring+JPA+Hibernate multiple databases

I am trying to connect to two databases with Spring and JPA. I am already connected to one database(sql server 2012), and I need to connect to another without changing too much stuff. I have app-context-dao.xml file which holds my hibernate and JPA configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<aop:aspectj-autoproxy proxy-target-class="false" />
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/SQLCMS" expected-type="javax.sql.DataSource" />
<jee:jndi-lookup id="dataSourceOracle" jndi-name="jdbc/razmjenskaDBSQL" expected-type="javax.sql.DataSource" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="hr.akd.cms.*" />
<property name="persistenceUnitName" value="caPersistenceUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.SQLServer2012Dialect" />
<property name="showSql" value="false" />
</bean>
</property>
<!-- ..................
Initialize additional Hibernate JPA related properties
if required
.................. -->
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactoryOracle"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceOracle" />
<property name="persistenceUnitName" value="userPersistenceUnit" />
<property name="packagesToScan" value="hr.akd.cms.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.SQLServer2012Dialect" />
<property name="showSql" value="false" />
</bean>
</property>
<!-- ..................
Initialize additional Hibernate JPA related properties
if required
.................. -->
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- .................. Transaction manager setup .................. -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManagerOracle" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryOracle" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- .................. Spring data - declare base packages for scanning,
all classes extending from data repositories will be available for autowire
.................. -->
<jpa:repositories base-package="hr.akd.cms.repository"
factory-class="hr.akd.cms.repository.impl.CMSCustomRepositoryFactoryBean" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="defaultPersistenceUnitName" value="caPersistenceUnit"/>
</bean>
I added entityManagerFactoryOracle, dataSourceOracle jndi transactionManagerOracle for my second database. When I start my app I got this
Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 2: entityManagerFactory,entityManagerFactoryOracle
My factory bean looks like this:
public class CMSCustomRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
extends JpaRepositoryFactoryBean<R, T, I> {
#SuppressWarnings("rawtypes")
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new CMSSearchFactoryFactory(entityManager);
}
private static class CMSSearchFactoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
private EntityManager entityManager;
public CMSSearchFactoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
#SuppressWarnings("unchecked")
protected Object getTargetRepository(RepositoryMetadata metadata) {
return new CMSCustomRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
// The RepositoryMetadata can be safely ignored, it is used by the
// JpaRepositoryFactory
// to check for QueryDslJpaRepository's which is out of scope.
return CMSCustomRepository.class;
}
}
You must make one of the dataSource and entityManagerFactory primary . primary = "true"
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
primary = "true">

Excluding Entity from Spring JPA packagesToScan

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>

Changing datasource connection url runtime

I am working on a project which uses spring + hibernate + mysql and c3p0 for connection pooling.
Currently the properties for the connection pool are loaded via properties defined outside the src. (eg: ${db_uname})
Everything starts fine when we create the spring bean.
It might so happen that the database to which we have connected is inaccessible for some reason, and we would like to switch hosts.
Need to implement a call back, where it is supposed to connect to the new host and re-initialize the pool
Any pointers on how to override the existing data source / connection pool gracefully would be of great help.
Here is how my spring config file looks like
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- Component scans -->
<import resource="component-scans-1.xml" />
<import resource="component-scans-2.xml" />
<util:properties id="serviceManagerProperties"
location="classpath:servicemanagers.properties" />
<!-- Properties file -->
<context:property-placeholder location="classpath:database.config.properties,classpath:framework.properties" />
<!-- context:annotation-config / -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<context:mbean-server id="mbeanServer" />
<context:mbean-export server="mbeanServer" default-domain="a.b.c" />
<bean id="cacheManager" factory-method="getInstance"
class="net.sf.ehcache.CacheManager" />
<bean class="net.sf.ehcache.management.ManagementService" init-method="init">
<constructor-arg ref="cacheManager" />
<constructor-arg ref="mbeanServer" />
<constructor-arg value="false" />
<constructor-arg value="false" />
<constructor-arg value="false" />
<constructor-arg value="true" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="persistenceXmlLocation" value="classpath*:META-INF/framework-persistence.xml" />
<property name="persistenceUnitName" value="PU-NAME" />
<property name="jpaProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
</prop>
<prop key="hibernate.ejb.cfgfile">hibernate.cfg.xml</prop>
<prop key="hibernate.generate_statistics">true</prop>
<!-- CONNECTION SETTINGS -->
<prop key="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</prop>
<prop key="hibernate.connection.url">
jdbc:mysql://${dbhost}/${dbschema}?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8
</prop>
<prop key="hibernate.connection.username">${dbuser}</prop>
<prop key="hibernate.connection.password">${dbpass}</prop>
<!-- CONNECTION POOLING -->
<prop key="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</prop>
<prop key="hibernate.c3p0.maxPoolSize">${hibernate.c3p0.maxSize}</prop>
<prop key="hibernate.c3p0.minPoolSize">${hibernate.c3p0.minSize}</prop>
<prop key="hibernate.c3p0.acquireIncrement">${hibernate.c3p0.acquireIncrement}</prop>
<prop key="hibernate.c3p0.idleConnectionTestPeriod">${hibernate.c3p0.idleTestPeriod}</prop>
<prop key="hibernate.c3p0.maxStatements">${hibernate.c3p0.maxStatements}</prop>
<prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
</props>
</property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
Assuming the database schema is right, lets say i get the database credentials and the host information in the event, i need to 're-set' the connection pool.
AbstractRoutingDataSource is a good choice.
Xml or annotation used like this:
<bean id="ds1" class="..c3p0.DataSource">
...
</bean>
<bean id="ds2" class="..c3p0.DataSource">
...
</bean>
<bean id="dataSource" class="..xxx.RoutingDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="ds1" value-ref="ds1"/>
<entry key="ds2" value-ref="ds2"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="ds1"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
...
</bean>
Then build a class to determine current datasoruce.
public class RoutingDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> holder = new ThreadLocal<String>();
protected Object determineCurrentLookupKey()
{
return holder.get();
}
public static void clear(){
holder.remove();
}
public static void setDataSourceKey(String key){
holder.set(key);
}
}
By the way, the 'try-finally' statement is boring!
try{
RoutingDataSource.setDataSourceKey("ds1");
myDao.doXXX();
}finally{
RoutingDataSource.clear();
}
<beans:bean id="dataSource"
class="org.springframework.aop.framework.ProxyFactoryBean">
<beans:property name="targetSource" ref="swappableDataSource" />
</beans:bean>
<beans:bean id="dummyDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" />
<beans:bean name="swappableDataSource"
class="org.springframework.aop.target.HotSwappableTargetSource">
<beans:constructor-arg ref="dummyDataSource" />
</beans:bean>
and some where in your code you can do this.
#Autowired
HotSwappableTargetSource swapable;
public void changeDatasource() throws Exception
{
swapable.swap(createNewSource();
}
ComboPooledDataSource createNewSource() throws Exception {
ComboPooledDataSource ds2 = new ComboPooledDataSource();
ds2.setJdbcUrl(url);
ds2.setDriverClass(driver);
ds2.setUser(username);
ds2.setPassword(password);
return ds2;
}
If you are asking for multiple databases connections ..it is possible with hibernate by creating multiple hibernate.cfg.file 's which is some what inappropriate
By following line you can acheive that .
SessionFactory sf = new Configuration().configure("somename.cfg.xml").buildSessionFactory();
When your primary connection not established you have load another hibernate configuration ...otherwise is wont possible .

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