Skip to main content

Command Palette

Search for a command to run...

Why ORM Sucks?

Published
•2 min read•View as Markdown

Small Companies may good to use ORM until we get perofrmance issue

Let Say why i am using sucks?

Example we can take, U want to get the all user orders. what u do?

Simple i will use User.findAll() and user.getOrder() thats it completed okay good

is it good practice for performance why not we are using orm and predefined methods there is catch

So to get All user we need to fire select from users. so 1 query and for every user we need to get orders so another query look like select from order where userId = ? so like this

N+1 query

I will make it simple okay i will use one query Like Select from SELECT u.name, o.amount FROM users u LEFT JOIN orders o ON u.id = o.user_id;

So i will get it in 1 Quey So tell me who is the best ?

Okay then it will tell this i have fetch use in query for the ORM okay fine but u need to know SQL behavior simple what point of ORM

Loss Of Control:

Let Say this Example : Get top 5 users who made highest total order amount in last 30 days

So we need to write the this Query

SELECT u.id, u.name, SUM(o.amount) AS total FROM users u JOIN orders o ON u.id = o.user_id WHERE o.created_at >= NOW() - INTERVAL '30 days' GROUP BY u.id, u.name ORDER BY total DESC LIMIT 5;

So we can use JPQL and Criteria Query ALL these Concepts

but there is cause here

  • Complex JPQL

  • Hard to tune

  • Hard to read

Come to this example so we need only 5 records but Using ORM we have to load all the data and limit is not support by ORM so u have to load all the data unnecessary

So Aggregations are not supported by ORM

Connection Pooling:

Issue:

@Transactional public void placeOrder() {

User user = userRepo.findById(1L).get(); // DB call → connection acquired

validateBusinessRules(); // NO DB calculateDiscount();

// NO DB sendEmailNotification();

// NO DB (slow) generateInvoicePdf(); // NO DB (slow)

orderRepo.save(order); // DB call

}

Why we need Connection unless we are making query , it stop block for other threads

Spring default use

spring.jpa.open-in-view=true

this make untill HTTP connection there db connection will there