I have the following code. The problem is that on the second line I get “org.apache.openjpa.persistence.TransactionRequiredException: Can only perform operation while a transaction is active”
The first line executed fine. What is my mistake?
//em is some EntityManager
String s = (String)em.createQuery("SELECT something FROM something WHERE something = something").getSingleResult();
em.createQuery("DELETE FROM something WHERE something = something").executeUpdate();
Read operations are handled differently from write operations in JPA. Write operations (be they create, updates or deletes) typically need to happen in the context of a transaction. The transaction boundary demarcates the calls you make to the session or entity manager, and defines when the transaction will be committed, (for example it could call commit on method call exit, when using container managed transactions).
For JPA, all calls to persist, remove, refresh and merge need to be done in a transaction. Query calls need to be performed in a transaction if they invoke
executeUpdate. And callinggetResultList()orgetUniqueResult()needs to be done in the context of a transaction if lock mode is notLockMode.NONE.Depending on your application needs you will use either container managed transactions (CMT), or bean managed transactions (BMT).
For CMT, make sure your persistence unit defines your datasource as JTA, and then annotate your class or method appropriately. For example:
And then annotate your class/method with the appropriate transaction type:
If using BMT, then you have to explicitly manage the transactions: