Careeroza
Real World Example
Flipkart-style Order Model
In a real store like Flipkart or Myntra, an order screen needs the customer, the line items with their products, and the payment. Here is the complete ShopEase mapping, with every association LAZY and the owning sides holding the foreign keys.
users 1 ───< orders 1 ───< order_items >─── 1 products >─── 1 categories
│ 1
└──── 1 payments (PK = order id, @MapsId)
users >───< products (wishlist join table) users 1 ───< cart_items >─── 1 productsPlacing an Order in a Service
@Service
@RequiredArgsConstructor
public class CheckoutService {
private final CartItemRepository cartItems;
private final OrderRepository orders;
@Transactional
public Order checkout(User user) {
List<CartItem> cart = cartItems.findByUserId(user.getId());
if (cart.isEmpty()) throw new IllegalStateException("Cart is empty");
Order order = new Order(user);
for (CartItem ci : cart) {
Product p = ci.getProduct();
p.decreaseStock(ci.getQuantity()); // dirty checking updates products.stock
order.addItem(new OrderItem(p, ci.getQuantity(), p.getPrice()));
}
order.recalculateTotal();
orders.save(order); // cascades to order_items
cartItems.deleteAll(cart);
return order;
}
}Example
SQL Hibernate runs for a cart with 2 items (MySQL, IDs generated by IDENTITY):
curl -X POST localhost:8080/api/checkout -H "Authorization: Bearer <token>"Example output
DEBUG org.hibernate.SQL : select c1_0.id,c1_0.added_at,c1_0.product_id,c1_0.quantity,c1_0.user_id from cart_items c1_0 where c1_0.user_id=?
DEBUG org.hibernate.SQL : select p1_0.id,p1_0.category_id,p1_0.description,p1_0.name,p1_0.price,p1_0.stock from products p1_0 where p1_0.id=?
DEBUG org.hibernate.SQL : select p1_0.id,p1_0.category_id,p1_0.description,p1_0.name,p1_0.price,p1_0.stock from products p1_0 where p1_0.id=?
DEBUG org.hibernate.SQL : insert into orders (status,total,user_id) values (?,?,?)
DEBUG org.hibernate.SQL : insert into order_items (order_id,price,product_id,quantity) values (?,?,?,?)
DEBUG org.hibernate.SQL : insert into order_items (order_id,price,product_id,quantity) values (?,?,?,?)
DEBUG org.hibernate.SQL : update products set category_id=?,description=?,name=?,price=?,stock=? where id=?
DEBUG org.hibernate.SQL : update products set category_id=?,description=?,name=?,price=?,stock=? where id=?
DEBUG org.hibernate.SQL : delete from cart_items where id=?
DEBUG org.hibernate.SQL : delete from cart_items where id=?
HTTP/1.1 201 Created
{"orderId":501,"status":"CREATED","total":1798.00,"items":2}Design Rules Used in Production
- Map
@ManyToOnefirst; add the@OneToManyside only when you navigate parent → children. - Make every association
LAZYand load what a screen needs with a fetch join or entity graph (next modules). - Turn link tables with data (cart, enrolment, membership) into entities.
- Store the price in
OrderItem: product prices change, but an old invoice must not.