ORM vs Raw SQL — Which one should YOU use? Two ways to talk to a database. Both powerful. Both have trade-offs. ORM (Object Relational Mapping) → You write code using models & methods → The ORM layer auto-generates the SQL → Returns hydrated model objects ✅ Faster development, less code, database agnostic ⚠️ But adds overhead & less control on complex queries Raw SQL → You write the exact SQL query → App sends it directly to the database → Returns raw rows ✅ Full control, better performance, ideal for complex joins & aggregations ⚠️ But requires SQL knowledge & more verbose code 🔑 Key Tradeoff: | | ORM | Raw SQL | |---|---|---| | Dev Speed | ⚡ High | Lower | | Query Control | Limited | Full | | Best For | CRUD & Rapid Dev | Complex Queries | 💡 My take: Use ORM for 80% of your daily CRUD work. Switch to Raw SQL when performance matters or queries get complex. In Spring Boot? Spring Data JPA = ORM, JdbcTemplate / Native Queries = Raw SQL. Best devs know when to use which! 🚀 #Java #SpringBoot #SQL #ORM #JPA #BackendDevelopment #DatabaseDesign #SoftwareEngineering
ORM vs Raw SQL: Choosing the Best Approach
More Relevant Posts
-
🚀 Spring Data JPA: Simplifying Database Access When building backend applications, handling databases can quickly become painful (SQL, mapping, boilerplate code...). 👉 That’s where Spring Data JPA makes a real difference. 🔹 What is it? Spring Data JPA is an abstraction that allows you to interact with your database using Java objects, based on the ORM (Object-Relational Mapping) concept. 🔹 How does it work? Define entities (@Entity) that map to database tables Create repositories (interfaces) Let Spring automatically generate SQL queries ➡️ Result: less code, more productivity. 🔹 Simple example: @Entity public class User { @Id @GeneratedValue private Long id; private String name; } public interface UserRepository extends JpaRepository<User, Long> { List<User> findByName(String name); } 🔥 With just one line, you can fetch data without writing any SQL. 💡 Why use it? ✔ Huge time saver ✔ Cleaner code ✔ Easier maintenance ✔ Perfect for modern applications 📌 In short: Spring Data JPA lets you focus on business logic instead of database plumbing. #Java #SpringBoot #JPA #Backend #SoftwareEngineering
To view or add a comment, sign in
-
-
I read two JetBrains articles recently that seem to completely contradict each other. One says: ❌ don't use data classes for entities in Kotlin. The other says: ✅ data classes are a great fit for entities. Same company. Opposite advice. The difference? One is about JPA. The other is about Spring Data JDBC. Here's why it matters. ── Spring Data JPA (Hibernate) manages entities as tracked, mutable objects. To do that, it needs to: → create proxy subclasses for lazy loading (class must be non-final) → call a no-arg constructor when loading from DB → inject fields via reflection after construction (fields must be mutable) Kotlin's data class breaks all three of these. Final. Immutable. No no-arg constructor. ── Spring Data JDBC is a completely different philosophy. No dirty checking. No proxies. No lazy loading. You call save() → SQL runs. You call findById() → result maps to your object. That's it. And because it uses constructor-based mapping, data classes are a natural fit. Immutable val fields? Great. final class? No problem. copy() to update instead of mutation? That's exactly the pattern. ── So "don't use data classes for entities" really means "...when using JPA." It's not a rule about Kotlin + databases in general. The two frameworks look similar from the outside — both are Spring Data, both talk to relational DBs. But they have fundamentally different models for how objects and databases interact. Once you see that, the contradiction disappears. 📝 Wrote a full breakdown on Medium — link in the comments. #Kotlin #SpringBoot #SpringData #JPA #Backend
To view or add a comment, sign in
-
-
I used to think using Spring Data JPA meant I didn’t really need to worry about SQL anymore. It felt too easy. 😅 I remember building a feature that looked perfectly fine in code, clean repositories, simple method names, everything “just worked.” Until I started testing it with more data and suddenly the API got slower… and slower. 🐢 Not crashing. Not failing. Just… slower. I opened the logs and saw a flood of queries. One for users, then one for each user’s orders. 📄📄📄 That’s when it hit me, I had no idea what queries were actually running behind my code. That moment was a bit uncomfortable everything “worked”, but I clearly didn’t understand what was happening. 😬 A few things became very real after that: JPA hides complexity, but it doesn’t remove it 🎭 JPA makes things easy, but it doesn’t make database behavior go away ⚠️ Just because you didn’t write the query doesn’t mean it’s efficient. You still need to understand what’s being generated 🔍 Lazy vs eager loading isn’t just theory, it directly impacts performance ⚙️ That innocent looking repository method? It can cause an N+1 problem real quick 🚨 In real systems, this doesn’t show up during basic testing. It shows up as slow endpoints, high DB usage and confusing debugging sessions. 🧩 Now, I still use JPA the same way but I don’t trust it blindly. I check queries, think about fetching strategies and pay attention to what’s happening underneath. 👨💻 What I learned: If you’re using JPA without understanding the queries, you are debugging in the dark. Have you ever been surprised by what JPA was doing behind the scenes? 🤔 #Java #SoftwareEngineer #SpringMVC #SpringBoot #SpringDataJPA
To view or add a comment, sign in
-
Day 23. I stopped writing raw SQL in my repositories. Not because SQL is bad. Because Spring Data JPA was already doing it for me. And I didn’t know. I used to write this: @Query("SELECT * FROM users WHERE email = :email", nativeQuery = true) User findByEmail(@Param("email") String email); It worked. Until I realized I was solving a problem the framework had already solved. Here’s what actually happens: → Queries tied directly to database structure → Harder to refactor when schema changes → Less readable for other developers → You bypass what Spring Data JPA already gives you That’s not flexibility. That’s unnecessary complexity. So I changed it. (see implementation below 👇) User findByEmail(String email); No SQL. Same result. Better readability. Now: → Let JPA generate simple queries → Use @Query only when needed → Native SQL only for edge cases The hard truth: → Writing SQL feels powerful → But overusing it makes your code rigid → Most queries don’t need it Using SQL is easy. Knowing when NOT to use it is what makes you a backend developer. Are you still writing SQL for simple queries? 👇 Drop it below #SpringBoot #Java #JPA #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
-
Ever felt like SQL is doing more work than your actual logic? Writing queries… mapping results… handling connections… It gets repetitive really fast. What if you could just work with objects instead? That’s where 𝗢𝗥𝗠 (𝗢𝗯𝗷𝗲𝗰𝘁 𝗥𝗲𝗹𝗮𝘁𝗶𝗼𝗻𝗮𝗹 𝗠𝗮𝗽𝗽𝗶𝗻𝗴) comes in. Instead of writing complex SQL queries, you interact with your database using Java objects. No more manually converting 𝗿𝗼𝘄𝘀 → 𝗼𝗯𝗷𝗲𝗰𝘁𝘀. ORM does it for you. Let’s simplify it Without ORM: • Write SQL queries • Execute them • Map ResultSet to objects manually With ORM: • Create a class • Map it to a table • Call methods like save(), findById() That’s it. Popular ORM frameworks we might know: 𝗛𝗶𝗯𝗲𝗿𝗻𝗮𝘁𝗲 (most widely used) 𝗝𝗣𝗔 (Java Persistence API – standard) Why developers love ORM: • Faster development (less boilerplate) • Focus on business logic, not SQL • Automatic mapping between objects & tables • Easy integration with Spring Boot But here’s the real insight ORM is powerful… but blindly using it can hurt performance. Sometimes, writing a custom query is still the better choice. So the goal isn’t to avoid SQL… It’s to use 𝗢𝗥𝗠 𝘀𝗺𝗮𝗿𝘁𝗹𝘆. Next time you call 𝘀𝗮𝘃𝗲() in your project, remember — there’s a lot happening behind the scenes. #CoreJava #JavaDeveloper #Spring #Framework #ORM #SpringBoot #SpringData #Hibernate #SoftwareDevelopment #SQL #BackEndDevelopment #MicroServices #Programming #aswintech #Database #BuildBetter
To view or add a comment, sign in
-
Are you building with Claude Code? Here is something to add to your Claude.md file to put a unique tag in each SQL statement. It works well, and you'll be VERY happy when attempting to identify the source of a long-running SQL statement. Exit and restart Claude to ensure it takes effect. Once working and tested on a few new SQL statements, tell Claude to go back and refactor all existing code and add the SQL tags based on the standard. Paste in everything below, and adjust relative to your project and database engine: ## SQL Tagging - Every SQL statement in Python code (batch jobs, APIs, shared modules) must include a comment tag as the first line of the SQL string identifying the source module and function/step. - Format: `/* module:function */` for batch jobs and shared code; `/* api:namespace:operation */` for API endpoints. - Examples: ```python # Batch job / shared code """ /* obsprocess:processpending */ SELECT "SystemObservationUUID" ... """ # API endpoint """ /* api:admin:get_logs */ SELECT "LogUUID" ... """ ``` - Tags appear in `pg_stat_statements`, `pg_stat_activity`, RDS Performance Insights, and PostgreSQL logs — enabling instant identification of which code path is responsible for a slow or blocking query. - When a shared function (e.g., `commonobs.py`) is called by multiple batch jobs, tag with the shared module name (e.g., `/* commonobs:ootreesync */`), not the calling job. - Tags must be kept in sync when SQL is refactored or moved between modules. - **Rename rule:** When renaming a batch job, API namespace, or shared Python module, scan all SQL strings across the codebase for tags referencing the old name and update them. SQL tags are plain text inside string literals — they will NOT be caught by IDE rename refactoring tools.
To view or add a comment, sign in
-
🚀 Still confused when to use One-to-One mapping in JPA? Most developers know @OneToOne… But very few understand how it actually works behind the scenes and when to use it correctly. This visual breaks it down in a clean + practical way 👇 🔍 What this image explains 👉 One-to-One Association means: Each record in one table is linked to exactly one record in another table. 💡 Real-world example: A User has exactly one UserDetails (email, phone, etc.) 🧩 How it works in Spring Data JPA ✔ @OneToOne → Defines the relationship ✔ @JoinColumn → Creates foreign key ✔ @MapsId → Shares primary key between tables ✔ cascade = ALL → Saves both entities together ✔ fetch = LAZY → Loads data only when needed 🗄️ Database Design Instead of storing everything in one table: 👉 JPA splits data into related tables users → basic info user_details → additional info 🔗 Connected using Primary Key + Foreign Key 💡 Why this matters ✔ Better data organization ✔ Cleaner architecture ✔ Avoids redundant data ✔ Improves performance in large systems 🔥 Pro Insight: Use One-to-One only when the relationship is strong and mandatory. Otherwise, you might be over-engineering your design. ⚡ Golden Rule: Think in objects, not tables — JPA handles the relationship for you. 💬 Question: Have you used @MapsId in your projects or still using basic mapping? #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #DatabaseDesign #LearningInPublic #Developers #TechContent
To view or add a comment, sign in
-
-
💾 Why “Indexing” in Databases Can Make or Break Your Application While working on backend projects, I realized something important: Even if your code is optimized… 👉 A slow database query can still kill performance. 🔍 What is Indexing? An index in a database is like an index in a book. Instead of scanning the entire table (slow), the database uses an index to quickly locate data (fast). 💡 Example Without index: - Database scans all rows With index: - Direct lookup, much faster ⚙️ Simple SQL Example CREATE INDEX idx_user_email ON users(email); Now, searching users by email becomes significantly faster. 🚨 But here’s the catch Indexes are not always good 👇 - They take extra storage - They slow down INSERT/UPDATE operations - Too many indexes can hurt performance 🧠 When should you use indexing? ✔ Frequently searched columns ✔ Columns used in WHERE, JOIN, ORDER BY ✔ High-read, low-write tables 📌 My takeaway: Database optimization isn’t just about writing queries — it’s about understanding how data is accessed. If you're building backend projects, start thinking beyond code… Start thinking about data performance. #Database #SQL #BackendDevelopment #Java #SpringBoot #SystemDesign #TechLearning
To view or add a comment, sign in
-
🔥 Day 41 of My Spring Boot Journey Today I explored some powerful features of Spring Data JPA that can significantly optimize database operations 📌 What I learned: ✅ Static Projection → Fetch only required fields using interface-based projections ✅ Dynamic Projection → Create flexible queries where the result type can be decided at runtime ✅ Custom Queries (JPQL & Native SQL) → Write optimized queries using @Query → Use @Param for named parameters → Perform UPDATE & INSERT using @Modifying and @Transactional 💡 Key takeaway: Instead of fetching entire entities, projections help improve performance and make APIs more efficient. Also understood the difference between: 🔹 SQL → works on tables 🔹 JPQL → works on entity classes 📁 Implemented all concepts with hands-on projects including: ✔ Static Projection ✔ Dynamic Projection ✔ Custom Queries Big thanks to my mentor for simplifying these advanced concepts 🙌 #SpringBoot #Java #BackendDevelopment #JPA #Hibernate #LearningInPublic #100DaysOfCode Hyder Abbas
To view or add a comment, sign in
-
-
⚡ Database Indexing — Why Some Queries Are Fast I used to think performance tuning meant writing complex SQL… Then I learned indexing can change everything 👇 What is an Index? An index helps the database find data faster without scanning every row. Think of it like: 📖 Book without index → search every page 📌 Book with index → jump directly to topic Same idea in databases. Without Index ❌ Full table scan ❌ Slower queries ❌ Poor performance at scale With Index ✅ Faster lookups ✅ Better query performance ✅ Lower database load Example Query: SELECT * FROM users WHERE email='abc@gmail.com'; Better with: CREATE INDEX idx_email ON users(email); Good columns to index ✔ Primary keys ✔ Frequently searched columns ✔ Join columns ✔ Filter columns Examples: email username foreign keys But over-indexing? ⚠️ Also a problem. Too many indexes can slow: inserts updates writes 💡 In backend systems, performance is often data-access design. Not just code optimization. 🧠 Key Insight: Sometimes a millisecond improvement starts with the database, not the API. What do you optimize first— queries or indexes? #Java #SQL #DatabaseIndexing #BackendDevelopment #PerformanceOptimization #SpringBoot
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Both are solid ways to talk to a database, and both come with trade-offs. With an ORM, you work with models and methods while the framework handles the SQL for you. It’s faster to build, easier to maintain, and great for day-to-day CRUD. The downside is that you give up some control, and performance can suffer when queries get complicated. Raw SQL is the opposite approach. You write the exact query you want and send it straight to the database. That gives you full control and usually better performance, especially for complex joins or heavy aggregations. The trade-off is more verbose code and the need to really know your SQL. My take? Use an ORM for most of your work. It handles around 80% of typical use cases really well. When performance matters or the query starts fighting the ORM, switch to raw SQL. In Spring Boot terms, Spring Data JPA covers the ORM side, while JdbcTemplate or native queries give you raw SQL power. The best devs don’t pick one forever — they know when to switch. #Java #SpringBoot #ORM #SQL #BackendDevelopment #SoftwareEngineering