Reputation: 5828
I am working on a service layer that logs to a database as it performs tasks. I want to ensure that this log doesn't roll back whenever an error occurs, as I should always keep a record of failed attempts. Below is sample code to explain what it is that I want.
@Transactional(rollbackFor=Exception.class)
public void performTask()
{
//Perform task 1
log("task1Complete");
//Perform task 2
log("task2Complete");
}
@Transactional()
public void log(String message)
{
//commit message to DB
//This should never rollback
}
I assume the way to do it is to start a new transaction but I'm not sure how.
Upvotes: 3
Views: 2600
Reputation: 2987
Use :
@Transactional(propagation = Propagation.REQUIRES_NEW)
Be aware that calling a @Transactional method on "this" will not open a transaction if you are using JDK Proxies or CGIL Proxies. You must use AspectJ instead or call it on another object to pass through its proxy.
Upvotes: 2
Reputation: 5032
you want to use:
@Transactional(propagation = Propagation.REQUIRES_NEW)
See: Propagation
Also, your TransactionManager must be configured to allow nested transactions.
Upvotes: 4