The Hybrid Approach
What you'll learn: How to strategically combine ORM and raw SQL in the same application to get the best of both worlds.
You don't have to choose between ORM or raw SQL—you can use both. The hybrid approach means using your ORM for the majority of your application's data access (where it provides productivity and maintainability) while selectively dropping to raw SQL for specific scenarios where performance or control is critical.
Why Mix Both?
Think of an ORM like an automatic transmission and raw SQL like a manual transmission. Most of the time, automatic is convenient and sufficient. But sometimes—like when you need maximum control climbing a steep hill—manual gives you the precision you need.
In practice, this means:
- ORM by default for CRUD operations, simple queries, and everyday object persistence
- Raw SQL for exceptions like complex reports, bulk operations, analytical queries, or performance-critical hotspots
How to Implement It
Most ORMs allow you to execute raw SQL within the same session or transaction. You maintain a single connection pool and transaction boundary, but selectively bypass the ORM's query generation when needed.
For example, use your ORM's session management and transaction handling, but when you hit a query that generates cartesian products or N+1 problems that eager loading can't solve, write that specific query in SQL. The result? You still get the benefits of the Identity Map Pattern, Unit of Work Pattern, and object mapping—just with hand-optimized queries where they matter.
The Balance
Start with ORM everywhere. Profile and measure. Only introduce raw SQL when you've identified actual bottlenecks. This keeps your codebase mostly consistent while allowing surgical optimizations.
Key Takeaway: The hybrid approach uses ORM for developer productivity on typical operations and raw SQL for performance-critical edge cases, giving you both maintainability and speed where each matters most.