Spring Entity Manager Factory using JNDI - spring

I am getting confused on how to get the entity Manager Factory in spring spring-datasource.xml using
I did the following :
spring-datasource.xml file:
<tx:jta-transaction-manager id="transactionManager" />
<tx:annotation-driven mode="proxy"
transaction-manager="transactionManager" />
<jee:jndi-lookup id="entityManagerFactory" jndi-name="jdbc/mysqldatasource" />
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="ebankingUnit"
transaction-type="JTA">
<jta-data-source>jdbc/mysqldatasource</jta-data-source>
<class>com.datamodel.Product</class>
<properties>
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.query-results-cache.expiry"
value="5000" />
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="hibernate.hbm2ddl.auto" value="none" />
</properties>
</persistence-unit>
but I am getting thid

which version of Spring are you using? You don't even need persistence.xml in the latest versions.
Here is the configuration using Spring 3.x, for oracle.
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- FactoryBean that creates the EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="ORACLE" />
<property name="showSql" value="false" />
</bean>
</property>
<property name="packagesToScan" value="blah.com..domain" />
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/myoracledb}" />
</bean>
Now define myoracledb jndi resource in your web.xml
<Resource name="myoracledb" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
maxActive="50"
url="your db url"
username="dbuser" password="dbpwd" />
Regards

Related

JobRepositoryFactoryBean error spring batch

I started to learn spring batch and I have a problem that when i want to
persist the state of the job in a database using JobRepositoryFactoryBean.
compiler displays :
"Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in class path resource [springConfig.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/core/simple/ParameterizedRowMapper"
but not error when i use MapJobRepositoryFactoryBean
I'm using spring 5
springconfig.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" xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="springbatch" />
<context:annotation-config />
<bean id="personneReaderCSV" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="input/personnes.txt" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="delimiter" value="," />
<property name="names" value="id,nom,prenom,civilite" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="targetType" value="springbatch.entities.Personne" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring_test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>springbatch.entities.Personne</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<job id="importPersonnes" xmlns="http://www.springframework.org/schema/batch">
<step id="readWritePersonne">
<tasklet>
<chunk reader="personneReaderCSV"
processor="personProcessor"
writer="personWriter"
commit-interval="2" />
</tasklet>
</step>
</job>
<bean id="daoPersonne" class="springbatch.dao.PersonneDaoImp">
<property name="factory" ref="sessionFactory"></property>
</bean>
<bean id="personWriter" class="springbatch.batch.PersonneWriter">
<property name="dao" ref="daoPersonne"></property>
</bean>
<bean id="personProcessor" class="springbatch.batch.PersonneProcess">
</bean>
<bean id="batchLauncher" class="springbatch.MyBean">
</bean>
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="Mysql" />
</bean>
<task:scheduled-tasks>
<task:scheduled ref="batchLauncher" method="message"
cron=" 59 * * * * * " />
</task:scheduled-tasks>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="org/springframework/batch/core/schema-drop-mysql.sql" />
<jdbc:script location="org/springframework/batch/core/schema-mysql.sql" />
</jdbc:initialize-database>
</beans>
but not error when i use :
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
You are using Spring Batch v2.2 with Spring Framework 5. That's not going to work properly as ParameterizedRowMapper has been removed in Spring Framework 4.2+ (hence the exception).
I recommend that you use Spring Batch v4.1 (since v2.x is not maintained anymore) and your issue should be fixed.
The best way to manage Spring dependencies is to let Spring Boot do it for you either by generating a project from start.spring.io or by using the Spring Boot BOM. With both ways, you will have the correct Spring projects dependencies that are known to work well together.

Spring JPA configuration issue

I have gone through almost all the posts here regarding Spring JPA configuration. Basically I want to implement JPA Pagination in my project and for that I need spring JPA support. But when I include the spring-data-jpa.jar in my project I get the following exception.
Caused by: java.lang.IllegalArgumentException: JBAS011470: Persistence unitName was not specified and there are 2 persistence unit definitions in application deployment deployment "CPCardApp.ear". Either change the application deployment to have only one persistence unit definition or specify the unitName for each reference to a persistence unit.
at org.jboss.as.jpa.container.PersistenceUnitSearch.ambiguousPUError(PersistenceUnitSearch.java:172)
at org.jboss.as.jpa.container.PersistenceUnitSearch.findWithinDeployment(PersistenceUnitSearch.java:152)
at org.jboss.as.jpa.container.PersistenceUnitSearch.findWithinApplication(PersistenceUnitSearch.java:86)
at org.jboss.as.jpa.container.PersistenceUnitSearch.findPersistenceUnitSupplier(PersistenceUnitSearch.java:76)
at org.jboss.as.jpa.container.PersistenceUnitSearch.resolvePersistenceUnitSupplier(PersistenceUnitSearch.java:63)
at org.jboss.as.jpa.processor.JPAAnnotationParseProcessor.getPersistenceUnit(JPAAnnotationParseProcessor.java:357)
at org.jboss.as.jpa.processor.JPAAnnotationParseProcessor.getBindingSource(JPAAnnotationParseProcessor.java:288)
at org.jboss.as.jpa.processor.JPAAnnotationParseProcessor.processMethod(JPAAnnotationParseProcessor.java:201)
at org.jboss.as.jpa.processor.JPAAnnotationParseProcessor.processPersistenceAnnotations(JPAAnnotationParseProcessor.java:138)
at org.jboss.as.jpa.processor.JPAAnnotationParseProcessor.deploy(JPAAnnotationParseProcessor.java:95)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:116) [jboss-as-server-7.1.3.Final-redhat-4.jar:7.1.3.Final-redhat-4]
... 5 more
persistence.xml (Note: I have 2 persistence units in my xml and Spring doesn't support that)
<?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="data01">
<jta-data-source>java:/MySqlDataDS</jta-data-source>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.cache.use_second_level_cache"
value="false" />
<property name="hibernate.id.new_generator_mappings" value="false" />
</properties>
</persistence-unit>
<persistence-unit name="cpaudit">
<jta-data-source>java:/MySqlAuditDS</jta-data-source>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.cache.use_second_level_cache"
value="false" />
<property name="hibernate.id.new_generator_mappings" value="false" />
</properties>
</persistence-unit>
</persistence>
You can have 2 persistence units. There are problems with your config (combo of using JBoss + Spring + JPA (Hibernate) + JTA). The proper configuration will depend on your version of JBoss and Spring.
No matter what you will need to have an xml file to define your JPA config with two entity managers.
Try something like this in a application-jpa-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:transaction="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<beans>
<bean id="entityManagerFactorData01" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaProperties">
<map>
<entry key="hibernate.cache.use_second_level_cache" value="false"/>
<entry key="hibernate.id.new_generator_mappings" value="false"/>
<entry key="hibernate.transaction.jta.platform" value-ref="jtaPlatform"/>
</map>
</property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jtaDataSource">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="password" value="${database.data01.password}"/>
<property name="url" value="${database.data01.url}"/>
<property name="username" value="${database.data01.user}"/>
</bean>
</property>
<property name="packagesToScan" value="com.app.entites.data01"/>
</bean>
<bean id="entityManagerFactoryCpaudit"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaProperties">
<map>
<entry key="hibernate.cache.use_second_level_cache" value="false"/>
<entry key="hibernate.id.new_generator_mappings" value="false"/>
<entry key="hibernate.transaction.jta.platform" value-ref="jtaPlatform"/>
</map>
</property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jtaDataSource">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="password" value="${database.cpaudit.password}"/>
<property name="url" value="${database.cpaudit.url}"/>
<property name="username" value="${database.cpaudit.user}"/>
</bean>
</property>
<property name="packagesToScan" value="com.app.entites.cpaudit"/>
</bean>
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" id="jpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>
<context:annotation-config/>
<jpa:repositories base-package="com.app.repo.data01" entity-manager-factory-ref="entityManagerFactorData01"/>
<jpa:repositories base-package="com.app.repo.cpaudit" entity-manager-factory-ref="entityManagerFactoryCpaudit"/>
<!-- ************ JpaTransactionManager *********** -->
<!--
This will depend on your JBoss and Spring version and your application.
You will need to work this out.
Getting your transactionManager correct could be difficult.
See the following project for more ideas:
https://github.com/manish-in-java/spring-data-jta/blob/master/src/main/resources/springContext.xml
-->
<transaction:annotation-driven/>
<bean class="java.lang.String" id="jtaPlatform">
<constructor-arg value="org.hibernate.engine.transaction.jta.platform.internal.JBossStandAloneJtaPlatform"/>
</bean>
<bean class="org.springframework.transaction.jta.JtaTransactionManager" id="transactionManager">
<property name="transactionManager">
<bean class="com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple"/>
</property>
<property name="userTransaction">
<bean class="com.arjuna.ats.jta.UserTransaction" factory-method="userTransaction"/>
</property>
</bean>
<!-- ************ JpaTransactionManager *********** -->
</beans>
</beans>

Setting up Spring JTA transaction in Jboss 7.1.1

Hello I am trying to setup spring JTA in myEclipse for Spring.Below are my configuration files:
applicationContent.xml where i have added two imports(note it do include schema locations)
<import resource="infrastructure.xml"/>
<import resource="classpath:**/persistence.xml"/>
infrastrutre.xml(unable to add schema due to input validations)
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jtaDataSource" ref="masterDataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<!-- <bean id="masterDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/test_JTA"></property>
</bean> -->
<jee:jndi-lookup id="masterDataSource" jndi-name="java:/Test_JTA" />
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- <property name="databasePlatform"
value="org.hibernate.dialect.MySQL5InnoDBDialect" /> -->
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="mainPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.abc.PaymentCard</class>
<jar-file>mysql-connector-java-5.1.23-bin.jar</jar-file>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
<property key="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property>
<property key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup</property>
</properties>
</persistence-unit>
</persistence>
I am getting error
JBAS010402: Unable to instantiate driver class "com.mysql.jdbc.Driver": org.jboss.msc.service.DuplicateServiceException: Service jboss.jdbc-driver.JTA_Test_war is already registered
I goggled this error but still haven't got any satisfactory answers.Kindly help
I am not sure about JBoss but for Glassfish there is an Ext directory for the Jars you want in the Classpath. So try to figure out how to deploy mysql-connector-java*.jar to your domain.
i know its late but, i believe i fixed this error by using a different factory class.
<property name="hibernate.transaction.factory_class" value="org.hibernate.ejb.transaction.JoinableCMTTransactionFactory"/>
hope it helps :)

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.

Spring Hibernate Configuration resulting in session NPE

I'm having issues properly setting up my Hibernate configuration. After trying to extend the HibernateDaoSupport into a GenericDao and extending those to class-specific daos, but when I call findByNamedQuery in my dao, getSession() throws an NPE.
When I tried switching to extending HibernateTemplate, the hibernateTemplate doesn't get instantiated properly, and is still null:
java.lang.NullPointerException
at org.springframework.orm.hibernate3.support.HibernateDaoSupport.getSession(HibernateDaoSupport.java:143)
at com.jmt.hibernate.dao.GenericDaoImpl.findByNamedQuery(GenericDaoImpl.java)
What am I missing??
I used maven2 to build the project,
1. added the hibernate plugin into my pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>3.0</version>
<configuration>
<components>
<component>
<name>hb2ddl</name>
<implementation>jpaconfiguration</implementation>
</component>
</components>
<componentProperties>
<drop>true</drop>
<outputfilename>output.sql</outputfilename>
<format>false</format>
<persistenceunit>MyEntityManager</persistenceunit>
<ejb3>true</ejb3>
</componentProperties>
</configuration>
</plugin>
2. defined my entity manager in persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="MyEntityManager" transaction-type="RESOURCE_LOCAL"> <!-- "JTA"> -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<class>com.jmt.model.UserEntity</class>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>CALLBACK</validation-mode>
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/><!-- org.hibernate.dialect.HSQLDialect" -->
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.connection.url" value="${jdbc.url}"/>
<property name="hibernate.connection.username" value="${jdbc.username}"/>
<property name="hibernate.connection.password" value="${jdbc.password}"/>
</properties>
</persistence-unit>
</persistence>
3. wired up my daos in applicationContext.xml:
<bean id="hibernateDaoSupport" abstract="true"
class="org.springframework.orm.hibernate3.support.HibernateDaoSupport">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="hibernateHelper" class="org.springframework.orm.hibernate3.HibernateTemplate" >
<constructor-arg ref="sessionFactory"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="hibernateManagedSession" value="true"/>
</bean>
<bean class="com.jmt.model.UserEntity"/>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="1" />
</bean>
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="2" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename"><value>messages</value></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="poolPreparedStatements" value="true"/>
<property name="defaultAutoCommit" value="true"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="30"/>
<property name="maxWait" value="1000"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="60"/>
<property name="logAbandoned" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="10000"/>
<property name="minEvictableIdleTimeMillis" value="60000"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>
<prop key="hibernate.jdbc.batch_size">15</prop>
<prop key="hibernate.connection.isolation">2</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.jmt.model</value>
<value>com.jmt.hibernate.dao</value>
</list>
</property>
</bean>
<bean id="userDao" class="com.jmt.hibernate.dao.UserDaoImpl">
<constructor-arg value="com.jmt.hibernate.dao.UserDaoImpl"/>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
4. even added a filter into my web.xml hoping that would inject the session properly:
<filter>
<filter-name>sessionLoadingFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
I didn't add in a manager yet, hoping that fewer layers would make SOMETHING work...
Any help/ideas would be much appreciated!
I think you should try to do openSession() rather doing getSession(). Because at that point there might be the case that your session is not opened and you are trying to get it and hence it will result in a NPE.
Hope this helps you. Cheers.
Yuck, I did not think about where the call to the dao was being made, and yes, that's why there wasn't an open session. Someone had used spring dwr to call the dao directly from a jsp file. Once I got rid of that and made the call from my Controller, the session was finally being instantiated properly. Thanks for the help, Japs!

Resources