Database connection exception using Spring, Hibernate, JPA e C3P0 - spring

I'm trying to configure my app to use C3P0 datasource (I can't use the datasource provided by the container).
But, when my app is starting, an exception has occurred:
The user must supply a JDBC connection
Bellow is my config files:
spring-config.xml:
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
</bean>
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
<property name="jdbcUrl" value="jdbc:oracle:thin:#host:1521:db" />
<property name="user" value="dbuser" />
<property name="password" value="passwd" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="pum" />
<property name="dataSource" ref="pooledDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
persistence.xml:
<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="AppPU" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.jdbc.batch_size" value="50" />
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
</properties>
</persistence-unit>
</persistence>
Exception:
java.lang.UnsupportedOperationException: The user must supply a JDBC connection
at org.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:54)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1573)
at org.hibernate.loader.Loader.doQuery(Loader.java:696)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2228)
at org.hibernate.loader.Loader.listUsingQueryCache(Loader.java:2157)
at org.hibernate.loader.Loader.list(Loader.java:2117)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:310)
at $Proxy286.getResultList(Unknown Source)
at com.embraer.core.jpa.DaoSupport.execQueryIndexedParameters(DaoSupport.java:327)
at com.embraer.core.jpa.DaoSupport.findByNamedQuery(DaoSupport.java:280)
at com.embraer.core.jpa.DaoSupport.findAll(DaoSupport.java:132)
at br.com.embraer.aheadpro.dao.imp.ConfigDAOImpl.findAll(ConfigDAOImpl.java:41)
at br.com.embraer.aheadpro.dao.ConfigRepoDAO.getAll(ConfigRepoDAO.java:35)
at br.com.embraer.aheadpro.service.ConfigService.refresh(ConfigService.java:27)
at br.com.embraer.aheadpro.service.ConfigService.getConfig(ConfigService.java:35)
at br.com.embraer.aheadpro.service.EmailService.init(EmailService.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:340)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:293)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130)
... 91 more
Thanks everybody!

Maybe this might help: http://thejavablog.wordpress.com/2010/11/26/java-lang-unsupportedoperationexception-the-user-must-supply-a-jdbc-connection/ , it basically says that there's something missing from persistence.xml (<provider>org.hibernate.ejb.HibernatePersistence</provider> or maybe hibernate.connection.provider_class-property ?), and Hibernate's ConnectionProviderFactory chooses to create a UserSuppliedConnectionProvider, which has getConnection defined as such:
public Connection getConnection() {
throw new UnsupportedOperationException("The user must supply a JDBC connection");
}
I also compared this with one of our own Hibernate/JPA -setups that works just fine with C3PO, and the only differences I spotted were that we pass some more properties to c3p0.ComboPooledDataSource and some properties to org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter when defining EntityManagerFactory in the Spring configuration xml:
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="${jdbc.dialectClass}" />
</bean>
</property>
But I doubt that could be it. There are no properties defined in our persistence.xml (at all).

Related

Multiple database Schema with Spring+Hibernate+JPA

I have same database schema database_1 and database_2 and want to configuration of these two database(database schema is same) and decide run time which database is use.
My persistence.xml is as below:
<persistence-unit name="first" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.model.AboutUs</class>
<class>com.model.AccessCards</class>
<properties>
<property name="hibernate.dialect" value="com.util.customMySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
<property name="hibernate.jdbc.batch_size" value="20"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
</properties>
</persistence-unit>
Persistence name second configure here as below :
<persistence-unit name="second" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.model.AboutUs</class>
<class>com.model.AccessCards</class>
<properties>
<property name="hibernate.dialect" value="com.util.customMySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
<property name="hibernate.jdbc.batch_size" value="20"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
</properties>
</persistence-unit>
Both persistence units load same classes .
and now my database-configure.xml as where i configure persistence unit with data source. as below first persistence unit name configare with datasource name datasource as :
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="first" />
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${datasource.driverClassName}" />
<property name="jdbcUrl" value="${datasource.url}" />
<property name="user" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="1" />
<property name="maxIdleTime" value="300" />
<property name="maxPoolSize" value="20" />
<property name="minPoolSize" value="3" />
<property name="maxStatements" value="300" />
<property name="testConnectionOnCheckin" value="true" />
</bean>
Now this code for configure second persistence unit name with data source name datasource5 as below :
<bean id="transactionManager5" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory5" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource5" />
<property name="persistenceUnitName" value="second" />
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean id="dataSource5" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${datasource.driverClassName}" />
<property name="jdbcUrl" value="${datasource5.url}" />
<property name="user" value="${datasource5.username}" />
<property name="password" value="${datasource5.password}" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="1" />
<property name="maxIdleTime" value="300" />
<property name="maxPoolSize" value="20" />
<property name="minPoolSize" value="3" />
<property name="maxStatements" value="300" />
<property name="testConnectionOnCheckin" value="true" />
</bean>
Now i use entity manager for save data in database and i am using mysql database . I got entity manager with persistence unit name first and second .
#PersistenceContext(unitName="first")
private EntityManager entityManager;
#PersistenceContext(unitName="second")
private EntityManager entityManager2;
Now entity manager save data in database using persist( object) method successfully .
entityManager.persist(project);
and entityManager2 save data in database using persist( object ) method successfully (No Exception here). But data does not store in database datbase_2 .
entityManager2.persist(project);
If I change the order of persistence unit first and second in persistence.xml then entityManager2 save data in database and entitymanager does not save data in database .
Any one have idea how i can make multiple entitymanager for same database schema .
There are a few limitations:
#Transactional corresponds to single TransactionManager.
JpaTransactionManager corresponds to single EntityManager(Factory).
Thus use separate methods with #Transactional annotation for each transaction manager:
#Transactional(transactionManager = "tmBeanName")
After that entity managers will work fine.
Also, some workaround exists to break the second limitation (DO NOT USE IT in this case):
It is possible to use single JtaTransactionManager instead of several JpaTransactionManager: distributed transaction will cover both entity managers and they will work fine too.

multiple entityManagerFactory for 2 different datasources

I want keep 2 datasources for 2 different databases (both are mysql) like below :
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
</bean>
<bean id="dataSource-A"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url-A}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory-A"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource-A" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<!-- spring based scanning for entity classes -->
<property name="packagesToScan" value="com.package-A" />
</bean>
<bean id="dataSource-B"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url-B}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory-B"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource-B" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<!-- spring based scanning for entity classes -->
<property name="packagesToScan" value="com.package-B" />
</bean>
Now when i do simply this, beanInitializer gives error that entityManagerFactory is not found.
How can i have multiple entityManagerFactory, for multiple data base and what is best way to do in xml.
I googled quite a lot, but none is able to solve my problem.
It works well if i define only one entityManagerFactory, I am just stuck to have miltiple entityManagerFactory in same application context.
Below is the example for keeping multiple persistence unit for different type of database. Similarly 2 unit can be kept for both of your sql databases.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="oraPersistent" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.kulhade.us.ora.entity.BilltoAddress</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>AUTO</validation-mode>
<properties>
<property name="javax.persistence.jdbc.driver" value="${db.driver}"/>
<property name="javax.persistence.jdbc.url" value="${db.url}"/>
<property name="javax.persistence.jdbc.user" value="${db.username}"/>
<property name="javax.persistence.jdbc.password" value="${db.password}"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.generate_statistics" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
<property name="hibernate.jdbc.batch_size" value="50"/>
</properties>
</persistence-unit>
<persistence-unit name="mongoPersistent" transaction-type="JTA">
<!-- Use Hibernate OGM provider: configuration will be transparent -->
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<class>com.kulhade.us.mongo.entity.Sample</class>
<class>com.kulhade.us.mongo.entity.SampleLine</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.ogm.datastore.provider" value="mongodb" />
<property name="hibernate.ogm.datastore.database" value="${mongodb.name}"/>
<property name="hibernate.ogm.mongodb.host" value="${mongodb.host}"/>
<property name="hibernate.ogm.datastore.port" value="${mongodb.port}"/>
<!--<property name="hibernate.ogm.datastore.document.association_storage" value="ASSOCIATION_DOCUMENT"/>
<property name="hibernate.ogm.mongodb.association_document_storage" value="COLLECTION_PER_ASSOCIATION"/>-->
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
</properties>
</persistence-unit>
</persistence>
These multiple persistence unit can be used in Spring orm. Below is the example for it.
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>org/springframework/orm/jpa/domain/persistence-multi.xml</value>
<value>classpath:/my/package/**/custom-persistence.xml</value>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="localDataSource" value-ref="local-db"/>
<entry key="remoteDataSource" value-ref="remote-db"/>
</map>
</property>
<!-- if no datasource is specified, use this one -->
<property name="defaultDataSource" ref="remoteDataSource"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="myCustomUnit"/>
</bean>

Spring and JTA error

I'm trying to integrate Spring JPA/Hibernate project with JTA using Atomikos.
I'm developing a small example which you can find in this repository
You can see all there (persistence.xml, applicationContext.xml, etc.). But I'm going to show a fragment of that files here:
persistence.xml:
<persistence-unit name="presistence-unit" transaction-type="JTA"> <!-- transaction-type="RESOURCE_LOCAL"> -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/ct</jta-data-source>
<class>org.sergio.jtaSpringProject.entities.Transfer</class>
<class>org.sergio.jtaSpringProject.entities.Client</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.connection.autocommit" value="false" />
<property name="hibernate.transaction.factory_class" value="org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory" />
<!-- <property name="hibernate.transaction.factory_class" value="com.atomikos.icatch.jta.hibernate3.AtomikosJTATransactionFactory" /> -->
<property name="hibernate.transaction.manager_lookup_class" value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup" />
</properties>
</persistence-unit>
applicationContext.xml:
<!-- Create proxy instances of Repository interfaces -->
<jpa:repositories base-package="org.sergio.jtaSpringProject.repositories"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>XADBMS</value>
</property>
<property name="xaDataSourceClassName">
<value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="URL">jdbc:mysql://localhost:3306/ct</prop>
<prop key="user">root</prop>
<prop key="password">root</prop>
</props>
</property>
<property name="maxPoolSize" value="3" />
<property name="minPoolSize" value="1" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
</bean>
</property>
<property name="persistenceXmlLocation">
<value>persistence.xml</value>
</property>
<property name="persistenceUnitName" value="presistence-unit" />
</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="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>
When I run this project I get next error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRepository': Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.sergio.jtaSpringProject.App.main(App.java:30)
Caused by: java.lang.NullPointerException
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:76)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:118)
at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:210)
at org.hibernate.jpa.internal.EntityManagerImpl.<init>(EntityManagerImpl.java:91)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.internalCreateEntityManager(EntityManagerFactoryImpl.java:345)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:388)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:541)
at com.sun.proxy.$Proxy17.createEntityManager(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:287)
at com.sun.proxy.$Proxy25.getDelegate(Unknown Source)
at org.springframework.data.jpa.provider.JpaClassUtils.isEntityManagerOfType(JpaClassUtils.java:46)
at org.springframework.data.jpa.provider.PersistenceProvider.fromEntityManager(PersistenceProvider.java:296)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.<init>(JpaRepositoryFactory.java:57)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.createRepositoryFactory(JpaRepositoryFactoryBean.java:79)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.doCreateRepositoryFactory(JpaRepositoryFactoryBean.java:69)
at org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport.createRepositoryFactory(TransactionalRepositoryFactoryBeanSupport.java:72)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:216)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 12 more
Why cannot Spring to instantiate both repositories?
I fix it!
Correct configurations is in https://github.com/serrodcal/spring-jta-atomikos
Basically, the problem was:
<jpa:repositories base-package="org.sergio.jtaSpringProject.repositories"/>
Jpa repository need to know entityManagerFactory and transactionManager. I solve this:
<jpa:repositories base-package="org.sergio.jtaSpringProject.repositories"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"/>

Error using OneToOne/ManyToOne with JPA and Multiple Data Sources

I've managed to configure JPA with multiple datasources, but I get the following error when bringing up my server (Websphere liberty):
org.hibernate.AnnotationException: #OneToOne or #ManyToOne onxxx.AccountBalance.currency references an unknown entity: xxx.Currency
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(T oOneFkSecondPass.java:109)
at org.hibernate.cfg.Configuration.processEndOfQueue( Configuration.java:1521)
at org.hibernate.cfg.Configuration.processFkSecondPas sInOrder(Configuration.java:1446)
at org.hibernate.cfg.Configuration.secondPassCompile( Configuration.java:1351)
at org.hibernate.cfg.Configuration.buildSessionFactor y(Configuration.java:1733)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>( EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityMan agerFactory(Ejb3Configuration.java:905)
The application deploys correctly if all the DAO are declared in the same database, but it fails if I move any of them to a second database. Is it possible to used JPA bags (OneToOne, ManyToOne, ManyToMany) with multiple data sources?
Relevant parts of the configuration:
Context:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/xxxwas"
cache="true" resource-ref="true" lookup-on-startup="false"
proxy-interface="javax.sql.DataSource" />
<bean id="h2dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url"
value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=3" />
<property name="username" value="test" />
<property name="password" value="test" />
</bean>
<tx:jta-transaction-manager />
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit .DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="h2" value-ref="h2dataSource" />
<entry key="mysql" value-ref="dataSource" />
</map>
</property>
<!-- if no datasource is specified, use this one -->
<property name="defaultDataSource" ref="dataSource" />
</bean>
<bean id="integrationEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="integrationEntityManagerFactoryPU" />
<property name="jtaDataSource" ref="h2dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter">
<!-- <property name="showSql" value="true" /> -->
<property name="database" value="H2" />
<!-- <property name="generateDdl" value="true" /> -->
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="databaseEntityManagerFactoryPU" />
<property name="jtaDataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter">
<!-- <property name="showSql" value="true" /> -->
<property name="database" value="MYSQL" />
</bean>
</property>
</bean>
<jpa:repositories base-package="xxx.impl.repository.integration"
query-lookup-strategy="create-if-not-found"
entity-manager-factory-ref="integrationEntityManagerFactory">
</jpa:repositories>
<!-- Configures Spring Data JPA and sets the base package of my DAOs. -->
<jpa:repositories base-package="xxx.impl.repository"
query-lookup-strategy="create-if-not-found"
entity-manager-factory-ref="entityManagerFactory">
</jpa:repositories>
Server.xml
<dataSource id="xxxwas" jndiName="jdbc/xxxwas" supplementalJDBCTrace="true" type="javax.sql.XADataSource">
<jdbcDriver javax.sql.ConnectionPoolDataSource="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource" javax.sql.DataSource="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" javax.sql.XADataSource="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" libraryRef="MySQLLib"/>
<properties databaseName="xxx" password="xxx" portNumber="3306" serverName="localhost" user="root"/>
</dataSource>
Web.xml
<resource-ref>
<res-ref-name>jdbc/xxxwas</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="databaseEntityManagerFactoryPU" transaction-type="JTA">
<class>xxx.impl.bo.AccountBalance</class>
<!-- WORKS IF DEFINED HERE -->
<!-- <class>xxx.impl.bo.Currency</class> -->
<properties>
<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.CMTTransactionFactory"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
<!-- <property name="hibernate.current_session_context_class"value="thread" /> -->
<!--<prop key="hibernate.transaction.flush_before_completion">false</prop>-->
<!--<prop key="hibernate.transaction.auto_close_session">true</prop>-->
<!--<prop key="hibernate.current_session_context_class">thread</prop>-->
<!--<prop key="javax.persistence.transactionType">JTA</prop>-->
<!--<prop key="hibernate.connection.release_mode">auto</prop>-->
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="net.sf.ehcache.configurationResourceName" value="ehcache_database.xml"/>
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.SingletonEhCacheProvider"/>
<!-- <property name="hibernate.archive.autodetection" value="class, hbm"/> -->
<!-- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> -->
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy"/>
<property name="hibernate.use_sql_comments" value="true"/>
<property name="hibernate.generate_statistics" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="integrationEntityManagerFactoryPU" transaction-type="JTA">
<!-- DOES NOT WORK IF DEFINED HERE -->
<class>xxx.impl.bo.Currency</class>
<properties>
<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.CMTTransactionFactory"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
I know its too late, but I had the same probleme.
I'm working on Oracle database, the same database with two schemas (users)
My solution was to give the first user access to all tables in the second user schema.
After that, on JPA Entity annotation, precise the schema for each entity.
This way, hibernate generate SQL queries with schema :
select field1, field2 from USER1.Table1 INNER JOIN USER2.TABLE2 ON .....
It work this way because user1 have access to user2 tables with a grant, but the two schemas must be in the same database, otherwise you have to create a dblink and a synonym.

EhCache CacheManager with multiple EntityManagerFactory

And one entityManagerFactory in spring-server.xml.
But i must generate one more entityManager, and i do it with
Persistence.createEntityManagerFactory("myotherpersistenceunitname");
but i get exception
Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:457)
at net.sf.ehcache.CacheManager.init(CacheManager.java:354)
at net.sf.ehcache.CacheManager.<init>(CacheManager.java:242)
at net.sf.ehcache.hibernate.EhCacheRegionFactory.start(EhCacheRegionFactory.java:70)
spring.xml:
<context:property-placeholder location="classpath:application.properties"/>
<context:component-scan base-package="merve.web.app" >
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
<context:annotation-config/>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />
<cache:annotation-driven />
<bean id="properties" class="merve.web.app.configuration.PropertyResourceConfiguration" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPU"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${database.target}"/>
<property name="showSql" value="${database.showSql}" />
</bean>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${database.driver}"/>
<property name="jdbcUrl" value="${database.url}"/>
<property name="user" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="minPoolSize" value="2"/>
<property name="maxPoolSize" value="10"/>
<property name="breakAfterAcquireFailure" value="false"/>
<property name="acquireRetryAttempts" value="3"/>
<property name="idleConnectionTestPeriod" value="300" />
<property name="testConnectionOnCheckout" value="true" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="jamesEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="jamesPU"/>
<property name="dataSource" ref="dataSourceJames" />
<property name="persistenceXmlLocation" value="classpath:META-INF/james-persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<bean id="dataSourceJames" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="jdbcUrl" value="jdbc:derby:../var/store/derby;create=true"/>
<property name="user" value="app"/>
<property name="password" value="app"/>
<property name="minPoolSize" value="2"/>
<property name="maxPoolSize" value="10"/>
<property name="breakAfterAcquireFailure" value="false"/>
<property name="acquireRetryAttempts" value="3"/>
<property name="idleConnectionTestPeriod" value="300" />
<property name="testConnectionOnCheckout" value="true" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
<!-- Ehcache library setup -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true" p:config-location="classpath:ehcache.xml"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" >
<property name="cacheManager"><ref local="ehcache"></ref></property>
</bean>
<dwr:configuration/>
<dwr:annotation-scan base-package="tuxi.web.app.service.dwr" scanRemoteProxy="true" scanDataTransferObject="true"/>
<dwr:url-mapping />
<dwr:controller id="dwrController"/>
</beans>
The problem, described here, and fixed in the source is not using the EhCache singleton correctly. The answer depends on which version of spring-context-support AND which version of EhCache you are using. For both, you need to be using EhCache 2.6 or greater:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.6.0</version>
</dependency>
Next, determine what to do based on your spring-context-support version:
If using Spring 3.1/3.2
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:shared="true"
p:config-location="classpath:ehcache.xml"/>
If using Spring 4.x
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:shared="false"
P:acceptExisting="true"
p:config-location="classpath:ehcache.xml"/>
Try naming both cacheManagers differently in ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
name="ehCacheManager1">
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
name="ehCacheManager2">

Resources