My goal is inserting a record into my database, then updating it in a new transaction.
I try it like this:
@PersistenceContext(unitName="Table")
private EntityManager manager;
@EJB
private ITransactionTest itt;
public void insertRecord(int i) throws RuntimeException{
Record record = new Record();
record.setId(i+"");
record.status(1);
manager.persist(record);
manager.flush();
itt.updateRecord(i);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateRecord(int i) throws RuntimeException{
Record record = manager.find(Record.class, i+"");
record.setStatus(2);
manager.flush();
}
However, it doesn't work. I also try to use getReference()
to retrieve my record, then it throws an exception saying entity not found. It seems that the entity no longer resides in the persistence context.
If I remove the annotation of REQUIRES_NEW
, it works and I can update my record successfully.
So how can I update my record in a new transaction? How can I keep entities in managed status in the persistence context crossing transactions?
It seems executing a update sql query using JPA can achieve my goal. But are there any other methods?
Best Regards,
Kajelas