Conversion exception with Hibernate 4 while JUnit testing with Spring - spring

I created the sessionFactory bean with an org.springframework.orm.hibernate4.LocalSessionFactoryBean class and the transactionManager bean with an org.springframework.orm.hibernate4.HibernateTransactionManager class.
On performing the JUnits tests the following shows up.
" Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'org.hibernate.SessionFactory' for property 'sessionFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.hibernate.SessionFactory] for property 'sessionFactory': no matching editors or conversion strategy found".
The Hibernate Core dependency version is 4.3.9 .
Please advice.
Below is my datasource.xml for the JUnit tests. The tests run under the dev profile. While the exact .xml code runs under the production profile for the main app smoothly.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<context:component-scan base-package="com.caveofprogramming.spring.test">
</context:component-scan>
enter code here
<beans profile="dev">`enter code here`
<context:property-placeholder
location="com/caveofprogramming/spring/web/test/config/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="javax.persistence.validation.group.pre-persist">
com.caveofprogramming.spring.web.dao.PersistenceValidationGroup
</prop>
<prop key="javax.persistence.validation.group.pre-update">
com.caveofprogramming.spring.web.dao.PersistenceValidationGroup
</prop>
<prop key="javax.persistence.validation.group.pre-remove">
com.caveofprogramming.spring.web.dao.PersistenceValidationGroup
</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.caveofprogramming.spring.web.dao</value>
</list>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource"></property>
<property name="sessionFactory" value="sessionFactory"></property>
</bean>
<tx:annotation-driven />
<bean id="exceptionTranslator"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor">
</bean>
</beans>
</beans>

You must pass reference to the bean, not value. So change this:
<property name="sessionFactory" value="sessionFactory"></property>
to
<property name="sessionFactory" ref="sessionFactory"></property>

Related

Repository Error - FactoryBean which is currently in creation returned null from getObject. in Atomikos distributed transaction

I am currently following tutorial of atomikos for distributed transaction using xml configuration. I get error in repository level with message factory bean which is currently in creation returned null from getObject. I think there is no any circular dependency in beans and database connection is also fine. When I removed repository from service implementation then there is no error.
Error i get in console
Error creating bean with name 'auctionServiceRequired_TX' defined in class path resource [spring-sender-mysql.xml]: Cannot resolve reference to bean 'auctionTarget' while setting bean property 'target'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auctionTarget': Unsatisfied dependency expressed through field 'quoteRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quoteRepository': Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'jpaMappingContext': FactoryBean which is currently in creation returned null from getObject
spring-sender-mysql.xml
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/springa-jpa.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd ">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>application.properties</value>
</property>
</bean>
<bean id="datasourceAtomikos-01"
class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName"><value>JDBC-1</value></property>
<property name="xaDataSource"><ref bean="xaDataSourceMySQL-01" /></property>
<property name="xaProperties">
<props>
<prop key="maxPoolSize">4</prop>
<prop key="uniqueResourceName">xads1</prop>
</props>
</property>
<property name="poolSize"><value>4</value></property>
</bean>
<bean id="xaDataSourceMySQL-01" class="com.mysql.cj.jdbc.MysqlXADataSource">
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="pinGlobalTxToPhysicalConnection"><value>true</value></property>
<property name="user"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
<property name="forceShutdown"><value>true</value></property>
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout"><value>300</value></property>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager"><ref bean="atomikosTransactionManager" /></property>
<property name="userTransaction"><ref bean="atomikosUserTransaction" /></property>
</bean>
<bean id="springJtaPlatformAdapter" class="io.trustaml.AtomikosJtaPlatform">
<property name="jtaTransactionManager" ref="transactionManager" />
</bean>
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<bean id="quoteEntityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasourceAtomikos-01"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.jta.platform">io.trustaml.AtomikosJtaPlatform</prop>
<prop key="javax.persistence.transactionType">JTA</prop>
</props>
</property>
<property name="packagesToScan" value="io.trustaml.model"/>
<property name="persistenceUnitName" value="quotePersistenceUnit" />
</bean>
<jpa:repositories base-package="io.trustaml.repository" entity-manager-factory-ref="quoteEntityManager"/>
<!-- Error in creating this bean -->
<bean id="auctionTarget" class= "io.trustaml.service.AuctionServiceImpl">
</bean>
<bean id="auctionServiceRequired_TX" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager" /></property>
<property name="target"><ref bean="auctionTarget" /></property>
<property name="transactionAttributes">
<props>
<prop key="confirm*">PROPAGATION_REQUIRED, -QuotesConfirmRollbackException, +QuotesNoRollbackException</prop>
<prop key="find*">PROPAGATION_SUPPORTS, readOnly</prop>
</props>
</property>
</bean>
<bean id="auctionServiceRequiresNew_TX" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager" /></property>
<property name="target"><ref bean="auctionTarget" /></property>
<property name="transactionAttributes">
<props>
<prop key="confirm*">PROPAGATION_REQUIRES_NEW, -QuotesConfirmRollbackException, +QuotesNoRollbackException</prop>
<prop key="find*">PROPAGATION_SUPPORTS, readOnly</prop>
</props>
</property>
</bean>
</beans>
Repository
public interface QuoteRepository extends JpaRepository<Quote, Long> {
List<Quote> findByStatus(String status);
}
Service Implementing repository
#Service
public class AuctionServiceImpl implements AuctionService{
private static final Logger LOGGER = LoggerFactory.getLogger(AuctionServiceImpl.class);
private static volatile boolean flipFlop = false;
#Autowired
private QuoteRepository quoteRepository;
// other business logic goes here
}

Spring applicationContext.xml: "The markup in the document following the root element must be well-formed"

I searched through the same questions but unfortunately I couldn't find the solution.
I face with the following exception:
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 32 in XML document from class path resource [applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 32; columnNumber: 2; The markup in the document following the root element must be well-formed.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:530)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:444)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at Main.main(Main.java:18)
Caused by: org.xml.sax.SAXParseException; lineNumber: 32; columnNumber: 2; The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1388)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$TrailingMiscDriver.next(XMLDocumentScannerImpl.java:1382)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:489)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:237)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:300)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
... 14 more
and this is my applicationContext.xml:
<context:component-scan base-package="com.springHibernate" />
<context:annotation-config />
<bean id="DataSource" 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/myapp" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<!-- Beans Declaration -->
<bean id="User" class="com.mycompany.myapp.core.model.User"/>
<bean id="Institute" class="com.mycompany.myapp.core.model.Institute"/>
<!-- User Service Declaration -->
<bean id="UserBoImpl" class="com.mycompany.myapp.core.bo.impl.UserBoImpl">
<property name="userDao" ref="UserDaoImpl" />
</bean>
<bean id="InstituteBoImpl" class="com.mycompany.myapp.core.bo.impl.InstituteBoImpl">
<property name="instituteDao" ref="InstituteDaoImpl" />
</bean>
<!-- User DAO Declaration -->
<bean id="UserDaoImpl" class="com.mycompany.myapp.core.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="InstituteDaoImpl" class="com.mycompany.myapp.core.dao.impl.InstituteDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
</beans>
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>com.mycompany.myapp.core.model.User</value>
<value>com.mycompany.myapp.core.model.Institute</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
I don't know what the reason of exception is ...
I appreciate your comments.
The <beans> tag is closed and then more bean definitions are added. Move the closing beans tag so it nests the bean definitions. Another related thing that can burn you with XML config files is using the format tool within your IDE. Never format the XML config with a tool, it can add additional whitespace to your xml which gets interpreted breaking your configuration.
In a nutshell your doing this:
<beans>
<bean id="1"/>
</beans>
<bean id="2"/>
<bean id="3"/>
When it should be like:
<beans>
<bean id="1"/>
<bean id="2"/>
<bean id="3"/>
</beans>
Full Configuration With Changes
<?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" 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">
<context:component-scan base-package="com.springHibernate" />
<context:annotation-config />
<bean id="DataSource" 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/mydb" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<!-- Beans Declaration -->
<bean id="User" class="com.mycompany.myapp.core.model.User"/>
<bean id="Institute" class="com.mycompany.myapp.core.model.Institute"/>
<!-- User Service Declaration -->
<bean id="UserBoImpl" class="com.mycompany.myapp.core.bo.impl.UserBoImpl">
<property name="userDao" ref="UserDaoImpl" />
</bean>
<bean id="InstituteBoImpl" class="com.mycompany.myapp.core.bo.impl.InstituteBoImpl">
<property name="instituteDao" ref="InstituteDaoImpl" />
</bean>
<!-- User DAO Declaration -->
<bean id="UserDaoImpl" class="com.mycompany.myapp.core.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="InstituteDaoImpl" class="com.mycompany.myapp.core.dao.impl.InstituteDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>com.mycompany.myapp.core.model.User</value>
<value>com.mycompany.myapp.core.model.Institute</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
</beans>

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 in standalone app

I am utilizing spring in non web application and I am using hibernate for working with DB. Problem I am experiencing is that while "registerShutdownHook();" does close spring context container it does not properly shut down and close resources for JPA so my connections to DB are getting maxed out.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="pu" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="showSql" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
I use configuration presented above to fire up JPA layer and use "#Transactional" annotations to inject EM's into DAO's.
Maybe someone could help me out what am I missing or how should I handle proper closing of JPA sessions in standalone environment ?
Thank you,
P.S. Exception I am getting is: java.net.SocketException: No buffer space available (maximum connections reached?): connect
1.Create transaction manager as follow :
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="persistanceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.orm.showsql}" />
<property name="generateDdl" value="${db.orm.generateDdl}" />
<property name="database" value="${db.type}"/>
<property name="databasePlatform" value="${db.orm.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
2.use persistance.xml(should be in classpath)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persistanceUnit" transaction-type="RESOURCE_LOCAL">
<description>Oracle db Persistence Unit</description>
<class>com.company.YourModelClass</class>
<properties/>
</persistence-unit>
</persistence>
3.Add following annotation in applicationContext.xml
<context:component-scan base-package="com.yourcompany.basepackage" />
4.annoatate your Entitymanager in service class like:
#PersistenceContext
private EntityManager em = null;
5.Inject TrasnsactionManager to :
private PlatformTransactionManager platformTransactionManager = null;
6.persist object like:
platformTransactionManager .persist(obj);
This is another example of application Context.xml with JPA. It works fine for me.
<context:property-placeholder location=”classpath:jdbc.properties”/>
<!– Connection Pool –>
<bean id=”dataSource” destroy-method=”close”>
<property name=”driverClass” value=”${jdbc.driverClass}”/>
<property name=”jdbcUrl” value=”${jdbc.url}”/>
<property name=”user” value=”${jdbc.username}”/>
<property name=”password” value=”${jdbc.password}”/>
</bean>
<!– JPA EntityManagerFactory –>
<bean id=”entityManagerFactory”
p:dataSource-ref=”dataSource”>
<property name=”jpaVendorAdapter”>
<bean>
<property name=”database” value=”${jdbc.database}”/>
<property name=”showSql” value=”${jdbc.showSql}”/>
</bean>
</property>
</bean>
<!– Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) –>
<bean id=”transactionManager”
p:entityManagerFactory-ref=”entityManagerFactory”/>
<!– Activates various annotations to be detected in bean classes for eg #Autowired–>
<context:annotation-config/>
<!– enable the configuration of transactional behavior based on annotations –>
<tx:annotation-driven transaction-manager=”transactionManager”/>
<!– Property Configurator –>
<bean id=”propertyConfigurer”>
<property name=”location” value=”jdbc.properties”/>
</bean>
<context:component-scan base-package=”com.test.dao”/>
</beans>

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