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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With