user3249433
user3249433

Reputation: 601

Java EE JTA and transaction rollback

I have a business service method that calls a Repository and i want to know how i can rollback a transaction.Say for example

@Transactionl
public class OrderService {

@inject
OrderRepository orderRepository;

@inject
InventoryRepository inventoryRepository;

@inject
Order order;

@inject
Item item;

public Order createOrder (Order order) {
    orderRepository.save(order);
}
public Item reduceInventory(Item item) {
     inventoryRepository.update(item);

}

What i want is when a checked exception like a SQL Exception occurs then I want both createOrder and reduceInventory should both be rolledback.Say after creating the order when i go reduceInventory if the item count is negative i dont ant the order to be created at all.

Thanks in advance

Upvotes: 0

Views: 3372

Answers (2)

Steve C
Steve C

Reputation: 19445

I'm assuming that you are using your OrderService from a web tier that has no associated transaction management.

That being the case then you should consider modifying your service code so that a single method executes the code that you need to be atomic:

@Transactional(rollbackOn = { SQLException.class, PersistenceException.class } )
public Order createOrder (Order order) {
    orderRepository.save(order);
    // I'm just guessing your update logic here:
    for (Item item: order.getItems()) {
        inventoryRepository.update(item)
    }
}

If any of the rollbackOn exceptions are thrown then the entire transaction will be rolled back.

Upvotes: 1

Abass A
Abass A

Reputation: 743

You can use rollbackfor attribute of Transactional annoation to rollback on specific Exception. By default spring will rollback only on unchecked exception but with this attribute you can specify an exception

@Transactional(rollbackFor=Exception.class)

you can see this post for more information: Annotation @Transactional. How to rollback?

Upvotes: 0

Related Questions