英文:
Cannot use an EntityTransaction while using JTA. Using non-jta
问题
I'm trying to do a CRUD and my persistence.xml have non-JTA-data-source but when I try to do something like create, update or delete I receive a message that says: Cannot use an EntityTransaction while using JTA
An example of my code:
@Transactional
public void destroy(T entity) throws Exception
{
EntityManager em = getEntityManager();
try
{
em.getTransaction().begin();
em.remove(em.merge(entity));
em.getTransaction().commit();
}
catch(Exception e)
{
em.getTransaction().rollback();
throw new Exception(e);
}
finally
{
if (em.isOpen())
{
em.close();
}
}
}
My persistence:
<persistence-unit name="namePU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>database</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
(Note: Code sections are provided as-is without translation.)
英文:
I'm trying to do a CRUD and my persistence.xml have non-JTA-data-source but when I try to do something like create, update or delete I receive a message that says: Cannot use an EntityTransaction while using JTA
An example of muy code:
@Transactional
public void destroy(T entity) throws Exception
{
EntityManager em = getEntityManager();
try
{
em.getTransaction().begin();
em.remove(em.merge(entity));
em.getTransaction().commit();
}
catch(Exception e)
{
em.getTransaction().rollback();
throw new Exception(e);
}
finally
{
if (em.isOpen())
{
em.close();
}
}
}
My persistence:
<persistence-unit name="namePU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>database</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
答案1
得分: 1
根据 Transactional
注解,似乎您正在使用Spring的事务管理。在这种情况下,尝试通过 em.getTransaction()
手动控制事务是没有意义的。此外,我不知道您如何获取 EntityManager
,但这可能会干扰Spring的事务管理。
要么坚持使用Spring的声明式事务管理方式(在我看来更好的想法),要么移除 Transactional
和 EntityManager
注入,自己管理持久单元和事务。
英文:
Based on the Transactional
annotation, it seems you are using Spring's transaction management. In that case, there is no point in trying to manually control the transaction via em.getTransaction()
. Also, I don't know how you get the EntityManager
, but that may interfere with Spring's transaction management as well.
Either stick to the Spring way of declarative transaction management (IMHO better idea), or remove Transactional
and EntityManager
injection and manage the PU and transactions yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论