This article is a note recording different views on pros and cons of ORM, specifically the Java JPA and Hibernate. There are two common approaches to brige the business data model and the database: ORM mapps data model to database, or typed-SQL use strong types SQL-like syntax to access db data. ORM is data-model driven while the typedSQL is db-driven. ORM includes JPA and Hibernate. Typed-SQL includes jOOQ and QueryDSL.
1 Pros and Cons of ORM/JPA
The following are key points made from the book Opinioned JPA with Querydsl.
Key pros of JPA are:
- JPA is standard
- Database independence
- Natural SQL-Java type mapping
- Convenient type conversion: allows customized attribute converter.
- Large objects: better thant JDBC.
- Flexible mapping: field to column mapping is flexbile.
- Unit of work: the first level cache of flushing at the end of a transaction.
- Declarative transactions
- Custom DTO objects
- Entity graph: defines what relations to load.
- Generate db schema or run SQL scripts
Key cons fo JPA are:
- Leaky abstraction: it is complex and one has to know every details to use it properly.
- Not enough: it works 80% of the time and needs low level funcitons everywhere.
- Update all columns
- Unit of work: supports only simple queries; It is big and slow.
- SQL use: many places SQL are required.
- Additioanl layer: 1st level cache and 2nd level cache.
ORM’s Biggest Value
In the issue debate: “JPA/Hibernate excels the most are the write scenarios, persisting complex graphs with added value in features like locking mechanisms.”
In jOOQ vs. Hibernate: “If, however, your writing becomes complex, i.e. you have to load a complex object graph with 20 entities involved into memory, perform optimistic locking on it, modify it in many different ways and then persist it again in one go, then SQL / jOOQ will not help you. This is what Hibernate has originally been created for.”
In What ORM have taught me disucssion, an author summarized:
- ORMs for domain model persistence (complex, stateful CRUD).
- SQL for relational model interaction (complex, stateless querying).
- Don’t use ORMs for querying. ORM is for OLTP, not batch processing or analysis.
- Don’t use SQL for complex CRUD.
Tuning ORM down
ORM maps all foreign keys as relations between ojbects. The relations can be defined on both directions. The big issue with JPA is that you don’t have fine control over the loading/saving of to-one relation.
For performance problems, understand to-one relations, control to-many relations and avoid the N+1 select problem.
Gaving King, the Hibernate creator, commented: “Hibernate are intentionally designed as “leaky abstractions” so that it’s possible to easily mix in native SQL where necessary. The leakiness of the ORM abstraction is a feature, not a bug!”
For batch processing and data analaysis, use jOOQ.