Skip to content

Instantly share code, notes, and snippets.

@dev-aritra
Created May 15, 2021 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev-aritra/11f7b9b2d43ea603bd92d8422cb80cc9 to your computer and use it in GitHub Desktop.
Save dev-aritra/11f7b9b2d43ea603bd92d8422cb80cc9 to your computer and use it in GitHub Desktop.
@Transactional
public Optional<Order> placeOrder(Long productId, Long userId) {
Optional<Product> product = productRepository.findByIdWithWriteLock(productId);
product.orElseThrow(() -> new RuntimeException("Invalid product id"));
if (product.get().getAvailableUnits() > 0) {
productRepository.decrementAvailableUnitsCountBy1(productId);
Order newOrder = new Order(userId, productId);
orderRepository.save(newOrder);
return Optional.of(newOrder);
}
return Optional.empty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment