Reputation: 167
I create a scheduler
that in the same transaction delete rows in DB
and insert new rows after delete.
But if the adding of rows fails, I lost my data because the delete was correctly.
How I can delete and add with the same transaction to avoid losing data in case of errors?
I want to do a delete and two different adds in the same table.
Upvotes: 2
Views: 1341
Reputation: 982
There are three cases:
If your code were everything starts is in a method a LocalServiceImpl class generated by service builder:
If your code is in a MVCActionCommand, you can use the BaseTransactionalMVCActionCommand as the parent class and implement your code in the doTransactionalCommand method.
If your code is outside of the LocalServiceImpl classes, you can always manually create a transaction using TransactionInvokerUtil:
import com.liferay.portal.kernel.transaction.*;
import com.liferay.portal.kernel.service.*;
import java.util.concurrent.*;
private _invokeTransactionally(Callable callable)
throws Throwable {
Class<?>[] rollbackForClasses = new Class<?>[1];
rollbackForClasses[0]=Exception.class;
try {
TransactionInvokerUtil.invoke(
TransactionConfig.Factory.create(
Propagation.REQUIRED, rollbackForClasses), callable);
}
catch(Exception e) {
// handle the exception
}
}
Callable callable = new Callable<Void>() {
Void call() throws Exception {
// here insert your code
return null;
}
}
Upvotes: 4