Real World Example

Inventory Service with EntityManager

A seller dashboard (like Flipkart Seller Hub or Meesho Supplier Panel) lets sellers add products, restock them and delist them. Here is that service written directly against the EntityManager:

@Service
@Transactional
public class InventoryService {

    private final EntityManager em;

    public InventoryService(EntityManager em) { this.em = em; }

    public Product addProduct(String sku, String name, BigDecimal price, int stock, String category) {
        Product p = new Product(sku, name, price, stock, category);
        em.persist(p);
        return p;
    }

    public Product restock(Long productId, int quantity) {
        Product p = em.find(Product.class, productId);
        if (p == null) throw new ProductNotFoundException(productId);
        p.setStock(p.getStock() + quantity);          // dirty checking -> UPDATE
        if (p.getStatus() == ProductStatus.OUT_OF_STOCK) p.setStatus(ProductStatus.ACTIVE);
        return p;
    }

    public void delist(Long productId) {
        Product p = em.find(Product.class, productId);
        if (p != null) p.setStatus(ProductStatus.DISCONTINUED);   // soft delete, keeps order history valid
    }

    @Transactional(readOnly = true)
    public Product get(Long productId) {
        return Optional.ofNullable(em.find(Product.class, productId))
                       .orElseThrow(() -> new ProductNotFoundException(productId));
    }
}

What the Database Sees

Request and SQL

Restocking product 42 with 30 units:

curl -X PATCH localhost:8080/api/seller/products/42/restock -H "Content-Type: application/json" -d '{"quantity":30}'

Example output

Hibernate: select p1_0.id,p1_0.category,p1_0.created_at,p1_0.description,p1_0.name,p1_0.price,p1_0.sku,p1_0.status,p1_0.stock from products p1_0 where p1_0.id=?
Hibernate: update products set category=?,description=?,name=?,price=?,status=?,stock=? where id=?

HTTP/1.1 200 OK
{"id":42,"sku":"SKU-BOAT-450","name":"Boat Rockerz 450","price":1499.00,"stock":150,"status":"ACTIVE"}

Tip: Notice delist does not delete the row. Old orders still reference the product, so e-commerce systems usually mark products discontinued instead of removing them.

Exercise

Exercise: Add a method changePrice(Long productId, BigDecimal newPrice) to InventoryService that rejects prices of zero or less with an IllegalArgumentException and returns the updated product.

Show answer
public Product changePrice(Long productId, BigDecimal newPrice) {
    if (newPrice == null || newPrice.signum() <= 0) {
        throw new IllegalArgumentException("Price must be greater than zero");
    }
    Product p = em.find(Product.class, productId);
    if (p == null) throw new ProductNotFoundException(productId);
    p.setPrice(newPrice);       // no merge/persist needed: p is managed
    return p;
}