#PersistenceContext entity manager cannot find an/any entity class which it appeared to have processed during container launch.
During persistence unit setup, it appears that the container finds and registers the entity:
2012-05-17 15:28:21,978 INFO [org.hibernate.cfg.annotations.Version] (main) Hibernate Annotations 3.4.0.GA
2012-05-17 15:28:21,997 INFO [org.hibernate.annotations.common.Version] (main) Hibernate Commons Annotations 3.1.0.GA
2012-05-17 15:28:22,004 INFO [org.hibernate.ejb.Version] (main) Hibernate EntityManager 3.4.0.GA
2012-05-17 15:28:22,039 INFO [org.hibernate.ejb.Ejb3Configuration] (main) Processing
PersistenceUnitInfo [
name: dashboardPu
...]
2012-05-17 15:28:22,069 WARN [org.hibernate.ejb.Ejb3Configuration] (main) Persistence provider caller does not implement the EJB3 spec correctly. PersistenceUnitInfo.getNewTempClassLoader() is null.
2012-05-17 15:28:22,146 INFO [org.hibernate.cfg.AnnotationBinder] (main) Binding entity from annotated class: scholastic.dashboard.dto.ReportRequest
2012-05-17 15:28:22,161 INFO [org.hibernate.cfg.annotations.QueryBinder] (main) Binding Named query: ReportRequest.getReportsByUser => from ReportRequest where userId = :userId
However, the later attempt to use that entity fails. I've verified that the entitymanager is indeed using dashboardPu (there are 3 persistence units in this ear) by dropping into the debugger and looking through the entitymanager>factory>persistenceUnit.
2012-05-17 15:28:54,730 DEBUG [org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter] (http-127.0.0.1-8080-2) Opening JPA EntityManager in OpenEntityManagerInViewFilter
2012-05-17 15:28:54,731 DEBUG [org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter] (http-127.0.0.1-8080-1) Using EntityManagerFactory 'dashboardEntityManagerFactory' for OpenEntityManagerInViewFilter
2012-05-17 15:28:54,731 DEBUG [org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter] (http-127.0.0.1-8080-1) Opening JPA EntityManager in OpenEntityManagerInViewFilter
2012-05-17 15:28:54,775 DEBUG [scholastic.dashboard.dao.ReportRequestDao] (http-127.0.0.1-8080-2) Get reports for secretuserid
2012-05-17 15:28:54,797 WARN [org.hibernate.hql.QuerySplitter] (http-127.0.0.1-8080-2) no persistent classes found for query class: from scholastic.dashboard.dto.ReportRequest where user_id = secretuserid
I got here by first having it fail to find the "ReportRequest.getReportsByUser" query using em.createNamedQuery(), then trying a query w/o using the full path name to the entity class from ReportRequest where userId = :userId, and then the query in the last code block line above.
Using JBoss 5.1, JPA 2, Hibernate 3.3 or 3.6, Spring 3.0.5.
Code snippets:
#Entity
#Table(name="td_report_request")
#NamedQueries({
#NamedQuery(name=ReportRequestDao.GET_REPORTS_BY_USER,
query="from ReportRequest where userId = :userId"),
})
public class ReportRequest extends SlmsGuidAbstract {...}
...
#Repository
public class ReportRequestDao {
#PersistenceContext
private EntityManager em;
public List<ReportRequest> getReportRequests(String userId) {
// TODO uncomment this line and remove the one after when we go to JBoss >= 6
// TypedQuery<ReportRequest> query = em.createNamedQuery(GET_REPORTS_BY_USER, ReportRequest.class);
// Query query = em.createNamedQuery(GET_REPORTS_BY_USER);
Query query = em.createQuery("from scholastic.dashboard.dto.ReportRequest where user_id = " + userId);
...
<bean id="dashboardEntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="lycea.ds.jndi-MySqlDS" />
<property name="persistenceUnitName" value="dashboardPu"/>
</bean>
...
<?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="dashboardPu" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<property name="jboss.entity.manager.factory.jndi.name" value="java:/dashboardPu"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.query.factory_class" value="org.hibernate.hql.ast.ASTQueryTranslatorFactory"/>
<property name="hibernate.connection.release_mode" value="auto"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Try adding annotated jpa class in persistance.xml inside tag <class/>
Related
I have simple maven EJB module using JPA. This is my persistance.xml file
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Persistence">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>GroupTypes.xml</mapping-file>
<properties>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#127.0.0.1:1521:E"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
I am using EJB Stateless Bean and I am trying to get all attributes from GroupTypes table. This is my bean implementation:
public class TestBean
{
private GroupTypes GroupTypes;
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
#WebMethod (operationName = "justTesting")
public boolean justTesting(#WebParam (name = "param") String value)
{
try
{
entityManagerFactory = Persistence.createEntityManagerFactory("Persistance");
entityManager = entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("Select name from GroupTypes");
List<AmmEdGroupTypes> result = query.getResultList();
return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
}
When I try to invoke this method I get exeption: javax.persistence.PersistenceException: No Persistence provider for EntityManager named Persistance.
My persistance.xml file is placed in folder resources/META-INF/persistance.xml, and if I am not using bean this solution works. Does anydbody have some idea why this is happening only in case when I am using bean?
I am using Intellij 12.1.1, Oracle 11g, Glassfish 3.1 server and JAVA 1.6.
I solved this problem in the following way:
Installed hibernate add-on on glassfish (using glassfish update tool)
On glassfish added jdb connection pool _AmmPool with properties: className, username,password,databaseName and url
On glassfish added jdbc resource jdbc/__amm binding with connection pool _AmmPool
Changed persistence.xml file
Changed pom.xml file
Copied the following libraries into glassfish domains/domain1/lib folder:
antlr-2.7.7
commons-collections-3.2.1,
dom4j-1.6.1,
ejb3-persistence-1.0.2.GA,
hibernate3-maven-plugin-3.0,
hibernate-commons-annotations-4.0.2.Final,
hibernate-core-4.2.2.Final,
hibernate-entitymanager-4.2.2.Final,
javassist-3.15.0-GA,
jta-1.1,
log4j-1.2.17,
oracle-jdbc-11.1.0.6.0-Production+,
slf4j-api-1.6.1
slf4j-log4j12-1.7.5
A also copied these libraries into glassfish/lib floder.
This is my new persistance.xml file: http://pastebin.com/xbEU9Tr0
And this is my pom.xml file: http://pastebin.com/uEjhW36
I am using Spring + JPA + Hibernate + EntityManager to talk to the database. I am getting 'A JTA EntityManager cannot use getTransaction()' error. Please provide your insights and help me resolve the issue.
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
... xmlns definitions...
xsi:schemaLocation="...">
<context:component-scan base-package="com.mycompany.myproject" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="myDAO" class="com.mycompany.myproject.dao.myDAO" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence ... xmlns definitions xsi:schemaLocation="..." version="1.0">
<persistence-unit name="TEST_DS">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/TEST_DS</jta-data-source>
<class>com.twinspires.exchange.model.Test</class>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" /> <!-- create-drop update -->
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
</properties>
</persistence-unit>
</persistence>
Exception Stack Trace (Excerpt)
15:47:43,340 INFO [STDOUT] DEBUG: org.springframework.transaction.annotation.AnnotationTransactionAttributeSource - Adding transactional method 'getName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
15:47:43,343 INFO [STDOUT] DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
15:47:43,356 INFO [STDOUT] DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [com.twinspires.exchange.dao.PicDAO.getName]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
15:47:44,114 INFO [STDOUT] DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl#c629e5] for JPA transaction
15:47:44,124 INFO [STDOUT] DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Could not rollback EntityManager after failed transaction begin
15:47:44,125 INFO [STDOUT] java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
15:47:44,125 INFO [STDOUT] at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:818)
15:47:44,126 INFO [STDOUT] at org.springframework.orm.jpa.JpaTransactionManager.closeEntityManagerAfterFailedBegin(JpaTransactionManager.java:412)
15:47:44,127 INFO [STDOUT] at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:381)
15:47:44,128 INFO [STDOUT] at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
15:47:44,129 INFO [STDOUT] at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
15:47:44,129 INFO [STDOUT] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
15:47:44,130 INFO [STDOUT] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
15:47:44,131 INFO [STDOUT] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
15:47:44,131 INFO [STDOUT] at $Proxy175.getName(Unknown Source)
Folowing is my dao class:-
public class MyDao implements IMyDao {
#PersistenceContext(unitName = "TEST_DS")
private EntityManager entityManager;
#Transactional
public String getName() {
final Query query = entityManager.createQuery("from TestTable");
final Object obj = query.getResultList().get(0);
return obj == null ? "Empty" : (String) obj;
}
}
Your help highly appreciated.
Remove the jta-datasource from persitence.xml, configure datasource as a bean j2ee:jdni-lookup and inject it into the LocalContainerEntityManagerFactoryBean
Remove this from persistence.xml
<jta-data-source>java:/TEST_DS</jta-data-source>
Configure the transaction-type to resource local
<persistence-unit name="TEST_DS" transaction-type="RESOURCE_LOCAL">
Change to your beans.xml
<j2ee:jndi-lookup id="dataSource" jndi-name="java:/TEST_DS"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
First of all I want to tell you I had the same problem. Researching about that I found this page with your post and the answer by "gkamal".
I think that the answer comes to say that if you are trying to use "global" JTA transaction in your application and it doesn't work then don't use it, use in its place a "local" JDBC transaction.
But if you need to use global JTA transaction then you must use it.
Well I am going to give you the solution I found in my resarch.
There are properties that are application server dependent. I use glassfish and this solution works fine, but I think you are using JBOSS (due to the value you are using in the jta-data-source in your persistence.xml) I will write the values for a JBOSS AS, but in JBOSS AS I don't prove it, I just prove it only in glassfish.
In your persistence.xml you have to put another property:
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
The value of this property is AP server dependent.
In your beans.xml file you have to take a look in the entity manager factory and transaction manager. Morover you have indicate in your web.xml which persistence units you are referencing in your application.
beans.xml
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="TEST_DS"/>
</bean>
In your transaction manager you are using entity manager factory but you don't have to do that. You have to indicate the transaction manager and user transaction used by your app server, this way
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="java:appserver/TransactionManager"/>
<property name="userTransactionName" value="java:comp/UserTransaction"/>
</bean>
The values of those properties are app server dependent (I use glassfish). I think you have to use the values for jboss ap:
<property name="transactionManagerName" value="java:/TransactionManager"/>
<property name="userTransactionName" value="UserTransaction"/>
But I didn't prove it.
Last, in glassfish I have to put in beans.xml (and I don't know why) the following bean (I think in jboss ap it isn't necessary but you might prove it)
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" >
<property name="persistenceUnits">
<map>
<entry key="TEST_DS" value="persistence/TEST_DS"/>
</map>
</property>
</bean>
In your web.xml you need reference the persistence units your application will use.
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/TEST_DS</persistence-unit-ref-name>
<persistence-unit-name>TEST_DS</persistence-unit-name>
</persistence-unit-ref>
I hope that the solution is of help for you. It works for me.
Well, my project was using EJB and JPA (with Hibernate), but I had to switch to Spring.
Everything was working well before that. The EJB used to inject the EntityManager, controled the transaction, etc.
Ok, when I switched to Spring, I had a lot of problems because I'm new on Spring. But after everything is running, I have the problem: the data is never saved on database. I configured my Spring to control the transactions, I have spring beans used in JSF, that has spring services that do the hard work. This services have a EntityManager injected and use #Transactional REQUIRED. This services pass the EntityManager to a DAO that call entityManager.persist(bean).
The selects appears to work well, the JTA transaction appears to work well to (I saw in log), but the entity is not saved!
Here is the log:
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter: doFilterInternal() (linha 136): Opening JPA EntityManager in OpenEntityManagerInViewFilter
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.beans.factory.support.DefaultListableBeanFactory: doGetBean() (linha 245): Returning cached instance of singleton bean 'transactionManager'
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: getTransaction() (linha 365): Creating new transaction with name [br.org.cni.pronatec.controller.service.MontanteServiceImpl.adicionarValor]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: doBegin() (linha 493): Opened new Session [org.hibernate.impl.SessionImpl#2b2fe2f0] for Hibernate transaction
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: doBegin() (linha 504): Preparing JDBC Connection of Hibernate Session [org.hibernate.impl.SessionImpl#2b2fe2f0]
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: doBegin() (linha 569): Exposing Hibernate transaction as JDBC transaction [com.sun.gjc.spi.jdbc40.ConnectionHolder40#3bcd4840]
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler: doJoinTransaction() (linha 383): Joined JTA transaction
INFO: Hibernate:
select
hibernate_sequence.nextval
from
dual
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: processCommit() (linha 752): Initiating transaction commit
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: doCommit() (linha 652): Committing Hibernate transaction on Session [org.hibernate.impl.SessionImpl#2b2fe2f0]
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.HibernateTransactionManager: doCleanupAfterCompletion() (linha 734): Closing Hibernate Session [org.hibernate.impl.SessionImpl#2b2fe2f0] after transaction
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.hibernate3.SessionFactoryUtils: closeSession() (linha 800): Closing Hibernate Session
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter: doFilterInternal() (linha 154): Closing JPA EntityManager in OpenEntityManagerInViewFilter
INFO: [Pronatec] - 04/04/2012 11:30:20 - [DEBUG] org.springframework.orm.jpa.EntityManagerFactoryUtils: closeEntityManager() (linha 343): Closing JPA EntityManager
In the log, I see it commiting the transaction, but I don't see the insert query (the Hibernate is printing any query). I also see that the Hibernate lookup to get the next value of the sequence ID. But after that, it never really inserts.
Here is the spring context configuration:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="PronatecPU" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="transactionManagerName" value="java:/TransactionManager" />
<property name="userTransactionName" value="UserTransaction" />
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
Here is my persistence.xml:
<?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="PronatecPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/pronatec</jta-data-source>
<class>br.org.cni.pronatec.model.bean.AgendamentoBuscaSistec</class>
<class>br.org.cni.pronatec.model.bean.AgendamentoExportacaoZeus</class>
<class>br.org.cni.pronatec.model.bean.AgendamentoImportacaoZeus</class>
<class>br.org.cni.pronatec.model.bean.Aluno</class>
<class>br.org.cni.pronatec.model.bean.Curso</class>
<class>br.org.cni.pronatec.model.bean.DepartamentoRegional</class>
<class>br.org.cni.pronatec.model.bean.Dof</class>
<class>br.org.cni.pronatec.model.bean.Escola</class>
<class>br.org.cni.pronatec.model.bean.Inconsistencia</class>
<class>br.org.cni.pronatec.model.bean.Matricula</class>
<class>br.org.cni.pronatec.model.bean.Montante</class>
<class>br.org.cni.pronatec.model.bean.ParametrosVingentes</class>
<class>br.org.cni.pronatec.model.bean.TipoCurso</class>
<class>br.org.cni.pronatec.model.bean.Turma</class>
<class>br.org.cni.pronatec.model.bean.UnidadeFederativa</class>
<class>br.org.cni.pronatec.model.bean.ValorAssistenciaEstudantil</class>
<class>br.org.cni.pronatec.model.bean.ValorHora</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="current_session_context_class" value="thread"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Here is my service that is injected in the managed bean:
#Service
#Scope("prototype")
#Transactional(propagation= Propagation.REQUIRED)
public class MontanteServiceImpl {
// more code
#PersistenceContext(unitName="PronatecPU", type= PersistenceContextType.EXTENDED)
private EntityManager entityManager;
// more code
// The method that is called by another public method that do something before
private void salvarMontante(Montante montante) {
montante.setDataTransacao(new Date());
MontanteDao montanteDao = new MontanteDao(entityManager);
montanteDao.salvar(montante);
}
// more code
}
My MontanteDao inherits from a base DAO, like this:
public class MontanteDao extends BaseDao<Montante> {
public MontanteDao(EntityManager entityManager) {
super(entityManager);
}
}
And the method that is called in BaseDao is this:
public void salvar(T bean) {
entityManager.persist(bean);
}
Like you can see, it just pick the injected entityManager and call the persist() method. The transaction is being controlled by the Spring, like is printed in the log, but the insert query is never printed in log and it is never saved.
I'm sorry about my bad english.
Thanks in advance for who helps.
EDIT:
Debugging, I saw that after each entityManager.persist(T), there's another action enqueued in the actionQueue of type "insert". After all, it's just queueing the actions and it's never executing them. Have anyone already faced this kind of problem?
Well, I finally solved my problem. There was some misconfiguration of the JTA. I don't know what could be, but I changed to RESOURCE_LOCAL and it worked.
First time I tried RESOURCE_LOCAL, I fell in trouble with the Glassfish validating the #PersistenceContext annotation and throwing "Could not resolve a persistence unit corresponding to the persistence-context-ref-name[...]". Then I found a good way to disable this validation: specifying
metadata-complete=true
on my web.xml. It says "Don't look at the annotations, because it's not necessary". Well, Spring is my container and it'll, by itself, look at annotations and configure what is needed. Then I don't need my server to do so.
After all, my configurations look like this:
web.xml:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true">
Spring's context.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="PronatecPU" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven />
persistence.xml:
<persistence-unit name="PronatecPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>jdbc/pronatec</non-jta-data-source>
<!-- ... -->
And my injected entityManager:
#PersistenceContext(type= PersistenceContextType.EXTENDED)
private EntityManager entityManager;
I hope this will help who has the same problem.
Try forcing a flush to the database.
entityManager.flush();
Our application use IBM WAS6.1 container with EJB3.0 feature pack. Transactions are container managed via EJB3.0 transactions started from ejb service bean. We use Spring for DI. There are 3 layers. Spring DAO, Spring Service and EJB3.0 Bean Service.
Now i when i try to use OpenJPA with WAS6.1. EntityManager is successfully injected into SpringDAO but container closes EntityManager before transaction commits. (Datasource is JNDI datasource)
Here is the stacktrace:
[1/4/12 9:23:17:769 EET] 0000001f ExceptionUtil E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "inquiryReconcilation" on bean "BeanId(PaymentSystemAppV1#PaymentSystemServiceEjbV1.jar#PaymentServiceBean, null)". Exception data: <openjpa-1.0.3-SNAPSHOT-r420667:649224 fatal user error> org.apache.openjpa.persistence.InvalidStateException: You have closed the EntityManager, though the persistence context will remain active until the current transaction commits.
at org.apache.openjpa.persistence.EntityManagerImpl.assertNotCloseInvoked(EntityManagerImpl.java:1068)
Our persistence.xml:
<?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="PaymentSystemEntityV1" transaction-type="JTA">
<jta-data-source>paymentDsSrv</jta-data-source>
<mapping-file>META-INF/namedQueries.xml</mapping-file>
/* entities */
<properties>
<property name="openjpa.TransactionMode" value="managed" />
<property name="openjpa.ConnectionFactoryMode" value="managed" />
<property name="openjpa.jdbc.DBDictionary" value="db2" />
<property name="openjpa.jdbc.Schema" value="PAYMENT"/>
<property name="openjpa.Log" value="DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
</properties>
</persistence-unit>
Spring Context:
<bean id="dbsJpaDao" parent="daoBase" class="com.kavuntek.dds.dao.impl.DbsJpaDaoImpl" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="entityManagerFactory" class="javax.persistence.Persistence"
factory-method="createEntityManagerFactory" >
<constructor-arg type="java.lang.String" value="PaymentSystemEntityV1"/>
</bean>
DAO:
public class DbsJpaDaoImpl implements IDbsJpaDao{
#PersistenceContext
private EntityManager entityManager;
public List<DbsLimit> subscriberLimitInquiry(){
...
return entityManager.createQuery(queryString);
}
EJB3.0 Service Bean:
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
#TransactionManagement(value = TransactionManagementType.CONTAINER)
#Interceptors(SpringBeanAutowiringInterceptor.class)
#Local(IDDSServiceV1.class)
public class DDSServiceBean iplements IDDSServiceV1{
#Autowired
private IDDSService ddsService;
public List<DbsInvoice> subscriberLimitInquiry()
...
I tried also spring LocalContainerEntityManagerFactory with these parameters:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="PaymentSystemEntityV1"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"/>
</property>
</bean>
Because transactions are not Spring managed, using WebSphereUowTransactionManager matters?
Nothing changed.
<bean id="transactionManager"
class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/>
Any opinions?
Thanks.
P.S. When i call entityManager.getTransaction() in DAO i get:
Exception data: java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
I'm trying to create JUnit tests for my JPA DAO classes, using Spring 2.5.6 and JUnit 4.8.1.
My test case looks like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:config/jpaDaoTestsConfig.xml"} )
public class MenuItem_Junit4_JPATest extends BaseJPATestCase {
private ApplicationContext context;
private InputStream dataInputStream;
private IDataSet dataSet;
#Resource
private IMenuItemDao menuItemDao;
#Test
public void testFindAll() throws Exception {
assertEquals(272, menuItemDao.findAll().size());
}
... Other test methods ommitted for brevity ...
}
I have the following in my jpaDaoTestsConfig.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:p="http://www.springframework.org/schema/p"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CONOPS_PU" />
</bean>
<bean id="groupDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.GroupDao" lazy-init="true" />
<bean id="permissionDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.PermissionDao" lazy-init="true" />
<bean id="applicationUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ApplicationUserDao" lazy-init="true" />
<bean id="conopsUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ConopsUserDao" lazy-init="true" />
<bean id="menuItemDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.MenuItemDao" lazy-init="true" />
<!-- enables interpretation of the #Required annotation to ensure that dependency injection actually occures -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<!-- enables interpretation of the #PersistenceUnit/#PersistenceContext annotations providing convenient
access to EntityManagerFactory/EntityManager -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access
to a single datasource -->
<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- enables interpretation of the #Transactional annotation for declerative transaction managment
using the specified JpaTransactionManager -->
<tx:annotation-driven transaction-manager="jpaTransactionManager" proxy-target-class="false"/>
</beans>
Now, when I try to run this, I get the following:
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#fa60fa6] to prepare test instance [null(mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest)]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(InjectionMetadata.java:159)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.(PersistenceAnnotationBeanPostProcessor.java:559)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$1.doWith(PersistenceAnnotationBeanPostProcessor.java:359)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:492)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:469)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:351)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:289)
... 18 more
It seems to be telling me that its attempting to store an EntityManager object into an EntityManagerFactory field, but I don't understand how or why. My DAO classes accept both an EntityManager and EntityManagerFactory via the #PersistenceContext attribute, and they work find if I load them up and run them without the #ContextConfiguration attribute (i.e. if I just use the XmlApplcationContext to load the DAO and the EntityManagerFactory directly in setUp ()).
Any insights would be appreciated.
These are the correct combinations of annotation + interface:
#PersistenceContext
private EntityManager entityManager;
#PersistenceUnit
private EntityManagerFactory entityManagerFactory;
But when using spring's transaction and entity manager support, you don't need the EntityManagerFactory at all.
The reason why you don't need EntityManagerFactory is because the creation of the EntityManager is responsibility of the transaction manager. Here's what happens in short:
the transaction manager is triggered before your methods
the transaction manager gets the EntityManagerFactory (it is injected in it), creates a new EntityManager, sets in in a ThreadLocal, and starts a new transaction.
then it delegates to the service method
whenever #PersistenceContext is encountered, a proxy is injected (in your Dao), which, whenever accessed, gets the current EntityManager which has been set in the ThreadLocal
I had to do the below combination, apart from adding spring-aspects jar to the project properties->Aspect Path and enabling spring aspects in sts. Ofcourse in my application context config file i defined the Entitymanagerfactory.
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext-domain.xml" })
public class ReaderTest extends AbstractJUnit4SpringContextTests {
#PersistenceContext
private EntityManager entityManager;
I too have same problem, When I added java-persistence api problem got resolved.
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>