Reputation: 1545
I have a @RequestScoped, @Transactional CDI bean injected in my REST interface:
@RequestScoped
@Transactional
public class myRestCall
{
@Inject
EntityHandlerService ehs; // contains @PersistenceContext
try
{
// execute business logic, access DB via ehs (JPA / Hibernate)
}
catch(Throwable t)
{
// log exception
// -> rollback transaction
}
}
Now I like to have a try / catch around the call of the business logic that I can log the exception properly. But I need to rollback the transaction manually, unless I throw the exception again what I do not like. So how can I force the transasction rollback here? I know how to do it, if it would be a EJB: We could do
@Resource
private SessionContext ctx;
and then
ctx.setRollbackOnly();
in the catch
close.
However, it is not an EJB and I cannot make an EJB out of it due to resource limits.
Upvotes: 2
Views: 2635
Reputation: 81
In case anyone is still looking for an answer, you can add the @Resource TransactionSynchronizationRegistry and then call setRollbackOnly();
@RequestScoped
class MyBean {
@Resource
private TransactionSynchronizationRegistry reg;
@Transactional
void yourmethod()
{
try {
// do stuff
} catch (Exception e) {
reg.setRollbackOnly();
}
}
}
If you can't use @Resource, you can lookup the trx resgistry with jndi:
java:comp/TransactionSynchronizationRegistry
Upvotes: 4
Reputation: 149
You can include a parameter rollbackOn="Exception.class" asociated to the @Transactional annotation.
But if yo do so, you must quit the "try-catch" block
Upvotes: 0