I was stuck in very hard situation for a moment.
The problem is: I have to use NativeQuery to delete and/or update some DB records in a JTA context (EJB).
my JPA persistence.xml looks like:
<persistence-unit name="OzsscJPANBPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/postgres_ozssc</jta-data-source>
<mapping-file>com/longz/ozssc/model/PostcodeEntity.xml</mapping-file>
<class>com.longz.ozssc.model.CustomerEntity</class>
......
If I use delete statement in this way:
@Override
public void remove(SmsdOutboxEntity toberemoved){
em.createNativeQuery("Delete from outbox where \"ID\" = " + toberemoved.getId()).executeUpdate();
TransactionRequiredException thrown:
root cause
javax.persistence.TransactionRequiredException:
Exception Description: No transaction is currently active
Such there is no transaction existing.
If we use transaction manually as:
@Override
public void remove(SmsdOutboxEntity toberemoved){
em.getTransaction().begin();
em.createNativeQuery("Delete from outbox where \"ID\" = " + toberemoved.getId()).executeUpdate();
/*em.flush();*/
em.getTransaction().commit();
IllegalStateException thrown:
root cause
javax.ejb.EJBException: EJB Exception: ; nested exception is:
java.lang.IllegalStateException: The method public abstract javax.persistence.EntityTransaction javax.persistence.EntityManager.getTransaction() cannot be invoked in the context of a JTA EntityManager.
Seems I can't use transaction manually, as JTA will manage transaction their self.
So my question is: How I can use Native Query to delete/update records in a JTA managed context?
Please advise.