Reputation: 47627
My question is rather simple, I would like to rollback a transaction created with @Transactional
on a method and still be able to return some results to the invoker.
@Transactional
public Object myMethod () {
...
// flag transaction for rollback
return myObject;
}
I saw this question which seemed to suggest to either throw an exception (not really what I am looking for) or invoke TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
, but eventually this also throws an exception (I am using JpaTransactionManager).
Any idea how I could achieve my goal?
Upvotes: 3
Views: 3112
Reputation: 19002
Before changing the data in DB, I always validate it. Because data must be valid when persisting the changes, I consider a correct behaviour to throw an exception (for the case of invalid data).
On the other hand, if you do not want to validate the data explicitly before persisting it, throw an overriden Exception that contain other fields that you need.
PS: In my logic I consider that rolling back a transaction has a critical cause, other than that data is not valid.
Trying to validate the data and to persist it in DB in the same service method seems to me bad design. Imagine you want to return back a container with validation messages if validation fails or to return a new entity, if the transaction was correct. What return type should your method have?
Upvotes: 1
Reputation: 2030
Try
@Transactional(readOnly=true)
It will rollback after leaving. But beware:
@Transactional
public void save(){
trySave();
}
@Transactional(readOnly=true)
private void trySave(){
...
}
This will ignore the readOnly
because the transaction-block starts in save()
!
Upvotes: 0