Changing datasource connection url runtime - spring

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 .

Related

Error when setting 2 DataBases without bean annotation using SpringData

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.

Spring MVC - have to manually flush() to get object to save

For some reason I can't get my object to save via hibernate unless I explicitly flush().
I am using Spring MVC
Part of the DAO that does the save
public final T saveOrUpdate(final T instance) {
context.currentSession().saveOrUpdate(instance);
context.currentSession().flush(); //TODO should not have to do this
return instance;
}
part of the web.xml file that allows queries from the view via AJAX
<filter>
<filter-name>Open Session In View Filter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Open Session In View Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
part of the spring configuration for transaction management
<context:property-placeholder location="classpath:environment.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${hibernate.connection.driver_class}" />
<property name="jdbcUrl" value="${hibernate.connection.url}" />
<property name="user" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="25" />
<property name="acquireIncrement" value="5" />
<property name="maxIdleTime" value="1800" />
<property name="numHelperThreads" value="5" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="entityInterceptor">
<bean class="org.mycompany.persistence.AuditTrailInterceptor"/>
</property>
<property name="hibernateProperties">
<props>
<!-- Hibernate Tweak to enhance performance -->
<prop key="hibernate.order_inserts">true</prop>
<!-- Hibernate Tweak to enhance performance -->
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<!-- Enable mapping of annotated hibernate classes -->
<property name="packagesToScan" value="org.mycompany" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
An example service method
#Service
#Transactional
class MyServiceImpl implements MyService {
...
#Override
public final void save(final MyObject obj) {
myObjectDao.save(obj);
}
Turns out is was a configuration issue between my root-context.xml and servlet-context.xml, I had to do the following:
I had to put the following in root-context.xml:
<!-- Load everything except #Controllers -->
<context:component-scan base-package="my.package">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
and in servlet-context.xml:
<!-- Search this package for annotated Spring Beans -->
<!-- Load #Controllers only -->
<context:component-scan base-package="my.package" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
note that use-default-filters="false" is important and is what I had a lot of trouble with originally, it appears that the servlet was overwriting the beans from root-context.xml

Spring + Hibernate4 Error CurrentSessionContext is always null

I'm using Hibernate 4 with spring 3.1 in a simple java Apllication.
I use the following code to create the Spring SessionFactory and then convert it into a hibernate SessionFactory:
pls waht is missing here ... Is this the right way to go?? Or do I miss something..? pls help!
.....
......
context=new ClassPathXmlApplicationContext(new String[]{"spring.xml"});
return (SessionFactory) context.getBean("mySessionFactory");
......
The CurrentSessionContext ofthe sessionfactory is always null!
So I cant execute
sessionFactory.getcurrentSession()
-> gives me an java.lang.NullPointer Exception
myBean Declarations in spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="myDataSource" 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/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory" name="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" scope="singleton">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>TblUrls.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.SunOneJtaPlatform</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref local="mySessionFactory" />
</property>
</bean>
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "mySessionFactory" />
</bean>
<!-- <bean id="myProductDao" class="hib.TblUrlsHome"> -->
<!-- <property name="sessionFactory" ref="mySessionFactory"/> -->
<!-- </bean> -->
</beans>
You have to do
sessionFactory.openSession();
This should solve your problem.

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>

hibernate 4 and spring 3 configuration issue

I use hibernate 4 with spring 3 and i configure it in xml like this:
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/jee http://www.springframework.org/schema/jee/spring-jee-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="propertiesConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/conf/jdbc.properties</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config />
<context:component-scan base-package="com.friendsalert"/>
<aop:aspectj-autoproxy/>
<!--
<bean id="log4jInitialization"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
<property name="targetClass"
value="org.springframework.util.Log4jConfigurer" />
<property name="targetMethod" value="initLogging" />
<property name="arguments">
<list>
<value>/WEB-INF/conf/log4j.xml</value>
this value is bad for production.
<value>10000</value>
</list>
</property>
</bean>
-->
<!-- ========================= RESOURCE DEFINITIONS ========================= -->
<!-- Local Apache Commons DBCP DataSource that refers to a combined database -->
<!-- (see dataAccessContext-jta.xml for an alternative) -->
<!-- The placeholders are resolved from jdbc.properties through -->
<!-- the PropertyPlaceholderConfigurer in applicationContext.xml-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="validationQuery" value="${jdbc.validationQuery}"/>
<property name="maxWait" value="${jdbc.maxWait}"/>
<property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
<property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
<!-- property name="loginTimeout" value="${jdbc.loginTimeout}"/ -->
</bean>
<!-- Transaction manager for a single JDBC DataSource -->
<!-- (see dataAccessContext-jta.xml for an alternative)
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="localSessionFactory"/>
</bean>
<bean id="localSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" depends-on="dataSource">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/friendsalert/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<!-- cache factory for hibernate 3.3 (surrently we use 3.2)-->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.charSet">UTF8</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop>-->
<prop key="hibernate.connection.aggressive_release">false</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.connection.autocommit">true</prop>
<!-- create / drop.. use exporter class instead!-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.friendsalert.dao.UserDao">
<property name="sessionFactory" ref="localSessionFactory"/>
</bean>
</beans>
and i use dao. When i do a transaction(save, get, update) it works in the first time and in second time i get an error that the transaction is closed.
I use #Transactional annotation in my dao for every function so i can't find out why there is no transaction.
can anybody tell me what i did wrong?
thanks
The unusual things about your configuration are :
<prop key="hibernate.connection.aggressive_release">false</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.connection.autocommit">true</prop>
I would just try without those lines.
From the reference doc : the autocommit mode is NOT recommended
hibernate.connection.autocommit
Enables autocommit for JDBC pooled connections (it is not recommended).
e.g. true | false
hibernate.connection.release_mode Specifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transaction. auto will choose after_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction

Resources