Not able to connect multiple PostgreSQL database using SPRING +HIbernate - spring

I need to connect multiple PostgreSQL database. I am using properties files to get database connection properties.
When I am running the application it is throwing an error as named query not found. But when I am removing configuration for second database,every thing is running fine.I have also tried by using catalog attribute of hibernate mapping. But it didnt yeild any result.
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:com/*****/config/jdbc.properties</value>
<value>classpath:com/*****/config/userLogin.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="order" value = "1"/>
</bean>
Hibernate connection to first PostgresSQL DataBase
<bean id="teDaDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value ="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value ="${jdbc.password}"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="teDaDataSource"/>
<property name ="mappingLocations" >
<list>
<value>classpath:Country.hbm.xml</value>
<value>classpath:AccountType.hbm.xml</value>
<value>classpath:Stocks.hbm.xml</value>
</list>
</property>
<property name = "hibernateProperties">
<props>
<prop key="dialect">${hibernate.dialect}</prop>
<prop key="show_sql">${hibernate.showsql}</prop>
<prop key="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="connection.autocommit">true</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="transaction.auto_close_session">true</prop>
</props>
</property>
</bean>
<bean id="abstractDaoTarget" class="com.****.generic.dao.GenericDaoImpl" abstract="true">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id = "transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" lazy-init="true">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
Hibernate configuration for second postgres database
<bean id="userLoginDaDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value ="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value ="${jdbc.password}"/>
</bean>
<bean id="userLoginSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="userLoginDaDataSource"/>
<property name ="mappingLocations">
<list>
<value>classpath:SecurityQuestion.hbm.xml</value>
</list>
</property>
<property name = "hibernateProperties">
<props>
<prop key="dialect">${hibernate.dialect}</prop>
<prop key="show_sql">${hibernate.showsql}</prop>
<prop key="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="connection.autocommit">true</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="transaction.auto_close_session">true</prop>
</props>
</property>
</bean>
<bean id="abstractDaoTarget" class="com.bhaskar.generic.dao.GenericDaoImpl" abstract="true">
<property name="sessionFactory">
<ref bean="userLoginSessionFactory"/>
</property>
</bean>
<bean id = "transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" lazy-init="true">
<property name="sessionFactory" ref="userLoginSessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
Class-Table mapping file
<hibernate-mapping>
<class name="com.*****.entity.Country" table="primary_data.country">
<id name="countryId" type="int">
<column name="country_id" not-null="true"/>
<generator class="increment"/>
</id>
<property name="countryName" type="string">
<column name="country_name" length="100" not-null="true"/>
</property>
<property name="countryDesc" type="string">
<column name="country_desc" length="100"/>
</property>
<property name="countryCapital" type="string">
<column name="country_capital" length="100" not-null="true"/>
</property>
</class>
<query name="getAllCountry">from Country </query>
</hibernate-mapping>
Property file config for second database
jdbc.driverClassName=org.postgresql.Driver
jdbc.databaseurl=jdbc\:postgresql\://localhost\:5432/userLogin
jdbc.username=******
jdbc.password=******
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.showsql=false
hibernate.hbm2ddl.auto=update
Property file config for first database
jdbc.driverClassName=org.postgresql.Driver
jdbc.databaseurl=jdbc\:postgresql\://localhost\:5432/*****
jdbc.username=*******
jdbc.password=******
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.showsql=false
hibernate.hbm2ddl.auto=update
Any help will be appreciated

The error message says:
Errors in named queries: getAllCountry
The getAllCountry query is
Select * from Country
That is not valid HQL. It's SQL. SQL != HQL. A valid HQL query would be
select c from Country c

Related

Spring Hibernate transaction committing but not saving in DB

Using Spring Boot, declarative transaction management.
Find operation is working fine but save is not reflecting changes in DB.
Please let me know if any more information is required.
this.getCurrentSession().saveOrUpdate(entity);
Spring Boot configuration:
#SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class,
TransactionAutoConfiguration.class,
WebSocketAutoConfiguration.class})
RDBM persistence beans definition:
<bean name="transactionAgnosticDataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
<property name="url" value="${spring.datasource.url}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
<property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
<property name="jmxEnabled" value="false"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnConnect" value="true"/>
<property name="testWhileIdle" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="timeBetweenEvictionRunsMillis" value="30000"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="validationQueryTimeout" value="5"/>
<property name="validationInterval" value="30000"/>
<property name="maxActive" value="50"/>
<property name="maxIdle" value="30"/>
<property name="initialSize" value="20"/>
</bean>
<bean name="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<property name="targetDataSource" ref="transactionAgnosticDataSource"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.test.xyz.persistence.model.AlertOptImpl</value>
<value>com.test.xyz.persistence.model.ChallengeImpl</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" rollback-for="java.lang.Throwable"/>
<tx:method name="*" rollback-for="java.lang.Throwable"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* com.test.xyz.core.service.*ServiceImpl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
</aop:config>
Service method:
#Override
public void test() {
TestResource testResource = testResourceDao.findById(1l).get();
testResource.setPosition(7);
testResource.save(testResource); //this calls this.getCurrentSession().saveOrUpdate(entity);
//testResource.flushSession();
}
Not getting any errors. Noticed the following in debug log:
o.s.o.h.HibernateTransactionManager : Initiating transaction commit
o.s.o.h.HibernateTransactionManager : Committing Hibernate transaction on Session
o.s.jdbc.datasource.DataSourceUtils : Resetting read-only flag of JDBC Connection [Transaction-aware proxy for target Connection
o.s.o.h.HibernateTransactionManager : Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey
o.s.jdbc.datasource.DataSourceUtils : Returning JDBC Connection to DataSource
o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [[com.
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request

Configure Spring JMS with JTA and Atomikos

I want to achieve the following:
i) we have a weblogic queue and external applications would be writing into the queue
ii)I have to write a stand-alone application which can read and write into this queue inside a transaction. i.e. the messages from the queue has to be persisted into DB. So in case of any error at any stage, the transaction should rollback and the message should be available in the queue again.
To achieve this I have done some self study and came across the below URL:
http://www.javaworld.com/article/2077963/open-source-tools/distributed-transactions-in-spring--with-and-without-xa.html?page=3
I have understood that I have to use JTA and XA resources for this. I have tried using Atomikos as the JTA Transaction manager following the below URL:
http://www.atomikos.com/Documentation/SpringIntegration
After trying whole day I have comeup with the following incomplete applicationContext.xml:
<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"
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">
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.provider.url">t3://somehost.corp.com:8011</prop>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
</props>
</property>
</bean>
<!--
This is an interface not a concreate class. Not sure what needs to go here for weblogic queue connection factory.
<bean id="xaFactory" class="javax.jms.XAConnectionFactory">
<property name="brokerURL" value="t3://somehost.corp.com:8011" />
</bean> -->
<bean id="ConnectionFactory" class="com.atomikos.jms.AtomikosConnectionFactoryBean"
init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="jms/AuditCF" />
<property name="xaConnectionFactory" ref="xaFactory" />
</bean>
<bean id="JtaTransactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="AtomikosTransactionManager" />
<property name="userTransaction" ref="AtomikosUserTransaction" />
</bean>
<bean id="AtomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close">
<property name="forceShutdown" value="false" />
</bean>
<bean id="AtomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout" value="300" />
</bean>
<bean id="myDestination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jms/AuditQ</value>
</property>
</bean>
<bean id="service" class="com.samples.AccountService">
<property name="jmsTemplate">
<ref bean="jmsTemplate" />
</property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="ConnectionFactory" />
</property>
<property name="defaultDestination">
<ref bean="myDestination" />
</property>
<property name="destinationResolver" ref="jndiResolver" />
</bean>
<!-- a class that implements javax.jms.MessageListener -->
<bean id="MessageListener" class="com.samples.Messages" />
<bean id="MessageListenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="transactionManager" ref="JtaTransactionManager" />
<property name="connectionFactory" ref="ConnectionFactory" />
<property name="messageListener" ref="MessageListener" />
<property name="destinationName" value="jms/AuditQ" />
<property name="concurrentConsumers" value="1" />
<property name="receiveTimeout" value="3000" />
<property name="sessionTransacted" value="true" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName">
<value>weblogic.jms.XAConnectionFactory</value>
</property>
</bean>
<bean id="jndiResolver"
class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="cache">
<value>true</value>
</property>
</bean>
<!-- <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="receiveTimeout">
<value>0</value>
</property>
<property name="destinationResolver" ref="jndiResolver" />
</bean> -->
<bean id="datasource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
init-method="init" destroy-method="close">
<!-- set an arbitrary but unique name for the datasource -->
<property name="uniqueResourceName">
<value>XADBMS</value>
</property>
<!-- set the underlying driver class to use, in this example case we use
Oracle -->
<property name="xaDataSourceClassName">
<value>oracle.jdbc.xa.client.OracleXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="user"><user></prop>
<prop key="password"><pwd></prop>
<prop key="URL">jdbc:oracle:thin:#host:3028/DB
</prop>
</props>
</property>
<!-- how many connections in the pool? -->
<property name="poolSize" value="3" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="com.samples">
</property>
<property name="dataSource">
<ref bean="datasource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.connection.isolation">3</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</prop>
<prop key="hibernate.transaction.manager_lookup_class">
com.atomikos.icatch.jta.hibernate4.TransactionManagerLookup
</prop>
</props>
</property>
</bean>
</beans>
As shown in the Spring-Atomikos integration example, the XAConnectionFactory has been mentioned as :
<bean id="xaFactory"
class="org.apache.activemq.ActiveMQXAConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
I am unable to find the related configuration I need to do for weblogic queue. I have tried using "weblogic.jms.XAConnectionFactory" as the class, but I get classnotfoundexception for that.
I dont have any experience working with JTA or XA. Kindly guide me.

Spring / Hibernate 4(non JPA) / Infinispan / Atomikos no transaction manager found

I'm using Tomcat7 and need JTA for Infinispan Cache. I am using Spring 3.x with Hibernate 4 (non JPA) and Atomikos for JTA. I can't find a transaction manager look up class in the Atomikos library or docs for Hibernate 4. All examples are for Hibernate version 3 or with use of JPA. Infinispan cannot find a transaction manager.
Here is my config:
<bean id="myDataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="rsname" />
<property name="xaDataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
<property name="xaProperties">
<props>
<prop key="URL">${db.url}</prop>
<prop key="user">${db.user}</prop>
<prop key="password">${db.pass}</prop>
</props>
</property>
<property name="maxPoolSize" value="50" />
<property name="minPoolSize" value="20" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingLocations" value="classpath*:hibernate/**/*.hbm.xml" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.cache.region.factory_class=org.hibernate.cache.infinispan.InfinispanRegionFactory
hibernate.cache.use_query_cache=true
hibernate.cache.use_second_level_cache=true
</value>
</property>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close">
<property name="forceShutdown" value="false" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction">
<property name="transactionTimeout" value="300" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager" depends-on="atomikosTransactionManager,atomikosUserTransaction">
<property name="transactionManager" ref="atomikosTransactionManager" />
<property name="userTransaction" ref="atomikosUserTransaction" />
<property name="allowCustomIsolationLevels" value="true" />
</bean>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*" rollback-for="Throwable" />
</tx:attributes>
</tx:advice>
Looking at the spring docs setting the jtaTransactionManager property on the LocalSessionFactoryBean should take care of things.
<property name="jtaTransactionManager" ref="transactionManager" />
Basically adding that to the definition of your bean should be enough.
Another note about your configuration, you are using <tx:annotation-driven /> so basically your <tx:advice .. /> does nothing only takes up space.

Spring JDBC store SchedulerFactoryBean can't trigger stored trigger manually

I have a clustered Quartz (version 2.1.6) scheduler that seems to work fine when deployed to a websphere cluster. The scheduler is created by Spring (version 3.1.3_RELEASE).
<bean id="scheduler-JDBC" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" abstract="true">
<property name="dataSource" ref="myDataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="jobFactory">
<bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
</property>
<property name="overwriteExistingJobs" value="true" />
<property name="quartzProperties">
<props>
<prop key="org.quartz.jobStore.isClustered">true</prop>
<prop key="org.quartz.jobStore.driverDelegateClass">${org.quartz.jobStore.driverDelegateClass}</prop>
<prop key="org.quartz.scheduler.instanceId">AUTO</prop>
<prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
</props>
</property>
</bean>
<bean id="cronScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" parent="scheduler-${scheduler:RAM}" depends-on="quartzDatabaseInitializer">
<property name="startupDelay" value="10" />
<property name="autoStartup" value="true" />
<property name="applicationContextSchedulerContextKey" value="applicationContext"/>
<property name="triggers">
<list>
<ref bean="cronTriggerStats" />
</list>
</property>
</bean>
The trigger and the job is stored in the database. The job is created with job_name="serverStatsJob" and job_group="DEFAULT"
The trigger is executing every 20 min.
How do I trigger the job manually?
I have tried
StdScheduler cronScheduler = (StdScheduler)springContext.getBean("cronScheduler");
cronScheduler.triggerJob(new JobKey("serverStatsJob", "DEFAULT"));
which works if I use a RAM store instead of JDBC
I have also tried creating a new trigger with the stored job
Trigger trigger1 = newTrigger()
.withIdentity("serverStatsJobTrigger", "userRequested")
.withSchedule(simpleSchedule()
.withRepeatCount(0))
.startNow()
.forJob(new JobKey("serverStatsJob", "DEFAULT"))
.build();
cronScheduler.scheduleJob(trigger1);
But it doesn't work either.
Could someone please help me
I found the problem myself.
The scheduler isn't executing in a transaction correctly.
I added a <tx:advice> for the scheduler and now it works.
<aop:config>
<aop:pointcut id="quartzSchedulerPointcut" expression="execution(* org.quartz.Scheduler.*(..))" />
<aop:advisor advice-ref="quartzSchedulerAdvice" pointcut-ref="quartzSchedulerPointcut" />
</aop:config>
<tx:advice id="quartzSchedulerAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

spring how to write config to support 2 database

i try to config a data source ----> mysql
the other data source ----> h2 in memory (embedded )
with the following config:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost/item"
p:username="" p:password="" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
<prop key="net.sf.ehcache.configurationResourceName">/ehcache.xml</prop>
</props>
</property>
<property name="packagesToScan" value="*************" />
</bean>
<!-- Spring transaction management -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="org.h2.tools.Server" class="org.h2.tools.Server" scope="singleton" factory-method="createTcpServer"
init-method="start" depends-on="org.h2.tools.Server-WebServer">
<constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,9092"/>
</bean>
<bean id="org.h2.tools.Server-WebServer" class="org.h2.tools.Server" scope="singleton" factory-method="createWebServer" init-method="start">
<constructor-arg value="-web,-webAllowOthers,true,-webPort,8082"/>
</bean>
<!-- notice that loading the Driver as a bean is unnecessary is most cases! u could safely remove this and the depends-on in the next bean -->
<bean id="H2DatabaseJDBCDriver" class="org.h2.Driver" scope="singleton" init-method="load" depends-on="org.h2.tools.Server"/>
<bean id="H2InMemoryDB"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
depends-on="org.h2.tools.Server">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:mem:appdb1;DB_CLOSE_DELAY=-1" />
<!-- ;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3 -->
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="H2InMemoryDBPool" class="org.apache.commons.pool.impl.GenericObjectPool">
<!-- Two connections: InMemoryEntityManagerFactory and transactionManager -->
<property name="minIdle" value="1"/>
<property name="maxWait" value="10"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="10"/>
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
</bean>
<bean id="H2InMemoryDBDSConnFactory" class="org.apache.commons.dbcp.DataSourceConnectionFactory">
<constructor-arg><ref bean="H2InMemoryDB"/></constructor-arg>
</bean>
<bean id="H2InMemoryDBPoolableConnFactory" class="org.apache.commons.dbcp.PoolableConnectionFactory">
<constructor-arg index="0"><ref bean="H2InMemoryDBDSConnFactory"/></constructor-arg>
<constructor-arg index="1"><ref bean="H2InMemoryDBPool"/></constructor-arg>
<constructor-arg index="2"><null/></constructor-arg>
<constructor-arg index="3"><null/></constructor-arg>
<constructor-arg index="4"><value>false</value></constructor-arg>
<constructor-arg index="5"><value>true</value></constructor-arg>
</bean>
<bean id="pooledInMemoryDB" class="org.apache.commons.dbcp.PoolingDataSource" depends-on="H2InMemoryDBPoolableConnFactory">
<constructor-arg><ref bean="H2InMemoryDBPool"/></constructor-arg>
</bean>
<bean id="sessionFactory2"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="pooledInMemoryDB">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
<property name="packagesToScan" value="********" />
</bean>
<bean id="transactionManager2"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
but its not work .
so my question is :
do i need to use 2 session factory or using dynamic data source switch ?
Thanks
I did find a typo that may cause you code to break.
Your second transactionmanager refers to the first sessionFactory. I think you want it to refer to the second transactionmanager. Try:
<bean id="transactionManager2"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory2" />
Regarding your question whether one has to use some sort of "dynamic data source switch" as described here, multiple data sources should just be fine.
i use
<jdbc:embedded-database id="embeddedDatasource" type="DERBY">
<jdbc:script location="classpath:test.sql"/>
</jdbc:embedded-database>
instead
it works

Resources