Java – hibernate / spring – rollback transaction in transaction
In view of this example code:
public class MyServiceImpl implements MyService { @Transactional public void myTransactionalMethod() { List<Item> itemList = itemService.findItems(); for (Item anItem : itemList) { try { processItem(anItem); catch (Exception e) { // dont rollback here // rollback just one item } } } @Transactional public void processItem(Item anItem) { anItem.setSomething(new Something); anItem.applyBehavIoUr(); itemService.save(anItem); } }
This is what I want to achieve:
>Only processitem (anitem); If an exception occurs, it should be rolled back. > If an exception occurs, mytransactionalmethod should continue, which means that for each should end. > If an exception occurs in mytransactionmethod but there is no exception in processitem (anitem), mytransactionmethod should be rolled back completely
Is there a solution that does not involve manually managing transactions (no comments)?
Editor: I'm considering using @ transactional (deployment = requirements_new), but I don't know if it can work in the same bean
Solution
This is a common misconception Spring transactions are implemented through proxies The agent is the packing of your class You are accessing the processitem method from the same class, that is, you are not through a proxy, so you will not get any transactions I explained the mechanism in this answer
Solution: if you need nested transactions, you need two separate spring beans, both of which must be represented by @ transactional