Reputation: 1272
I have a @Stateless
-Bean which performs some Database operations in a single method
public void doOperation(){
User u1 = createNewUser()
User u2 = createNewUser()
User updated = mergeUser(u1,u2) // just as an example
// should write to database now!
otherBlockingOperation()
}
However the changes are not visible in the database until the blocking operation finished and therefore not visible in the frontend.
I thought this is because the transaction is not committed until otherBlockingOperation()
is finished. I then wrapped otherBlockingOperation()
in a Thread, which did not work again.
However I think the real problem is merge
which will only update the entity after the method is done. How can I change the values of Object instantly?
Edit:
@PersistanceContext
private EntityManager em;
mergeUser(T entity){
em.merge(entity);
em.flush();
}
Upvotes: 2
Views: 185
Reputation: 4114
Depending on the actual business requirements, a possible solution would be to move the otherBlockingOperation()
method to a new @Stateless
bean and mark the method as @Asynchronous @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
. This will effectively run the method in a new thread and new transaction. You would simply @Inject
the new bean and call the otherBlockingOperation()
method.
A new transaction might (or might not) be a valid option, depending on business needs (i.e. the new transaction might fail, while the original transaction might succeed). However, the update will be committed in DB sooner (but still after the original transaction is committed) without dependency on the otherBlockingOperation()
process (or even successful commit).
Upvotes: 4