TransactionRequiredException Executing an update/delete query

后端 未结 20 2138
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 15:29

Hi I am using hibernate JPA with spring and mongodb and i am running my application on Glassfish-4.0.

My service class is :

@Component
public class T         


        
20条回答
  •  误落风尘
    2020-12-02 15:37

    I am not sure if this will help your situation (that is if it stills exists), however, after scouring the web for a similar issue.

    I was creating a native query from a persistence EntityManager to perform an update.

    Query query = entityManager.createNativeQuery(queryString);
    

    I was receiving the following error:

    caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query

    Many solutions suggest adding @Transactional to your method. Just doing this did not change the error.

    Some solutions suggest asking the EntityManager for a EntityTransaction so that you can call begin and commit yourself. This throws another error:

    caused by: java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead

    I then tried a method which most sites say is for use application managed entity managers and not container managed (which I believe Spring is) and that was joinTransaction().

    Having @Transactional decorating the method and then calling joinTransaction() on EntityManager object just prior to calling query.executeUpdate() and my native query update worked.

    I hope this helps someone else experiencing this issue.

提交回复
热议问题