Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction required exception on execute update for JPQL update query

I get this error when I try to run this code.

Error:

javax.persistence.TransactionRequiredException: executeUpdate is not supported for a Query object obtained through non-transactional access of a container-managed transactional EntityManager

Code: (_ut is a UserTransaction object)

public void setMainCategory(Integer deptId, Integer catId) {

        try {
            Query setmain = _entityManager.createNamedQuery("Category.setAsMain");
            Query removeMain = _entityManager.createNamedQuery("Category.removeMain");
            setmain.setParameter("categoryId", catId);
            Department d;
            d=_entityManager.find(Department.class, deptId);
            removeMain.setParameter("department", d);
            _ut.begin();
            removeMain.executeUpdate();
            _ut.commit();
            _ut.begin();
            setmain.executeUpdate();
            _ut.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I have other functions that are identical in implementation and they do not throw this error.

Any suggestions would be greatly appreciated.

Thanks.

like image 1000
user2233876 Avatar asked Apr 01 '13 22:04

user2233876


1 Answers

You are using an EntityManager to get the Named Queries and also using an (what I think is) injected UserTransaction.

See that the error message says "...Query object obtained through non-transactional access...". This means you are getting the "NamedQuery" through non-transactional access, because the EntityManager is not in the same transaction as _ut. So, you first join the EntityManager to the UserTransaction then you get and execute the query.

Finally your block should look like:

@PersistenceContext(unitName = "myPU")
EntityManager em;

@Inject
UserTransaction ut;

public void doSomeStuff()
{
    ut.begin();
    em.joinTransaction();

    em.createNamedQuery("query1").executeUpdate();

    ut.commit();
}
like image 182
Joe Almore Avatar answered Oct 20 '22 02:10

Joe Almore