Hibernate — a silver bullet for Java Persistence (Part 1)
There is a long term debate about the pros. and cons. of JPA or Hibernate. (In this article I will use the terms interchangeably). Some authors claim that JPA takes the control over SQL away. They say that since Hibernate, as a tool, does not perform 100% of required “database tasks”, sooner or later the user will hit a problem. And their solution to that problem is … not using JPA!
In this series I will show that Hibernate is awesome for what it does. And when its limits are hit, a complementary tool should be used.
In short, if I go hiking several times a year, I don’t burn my car. Because otherwise I will need to hike to my office every morning!
What does Hibernate do very well?
- ORM. The mapping. Since we program in Java, we want to use objects. We want type safety and intellisense.
- Object retrieval and persistence. We can find() and persist() back object hierarchy with the changes easily.
What does Hibernate do less well?
Queries. Actually there is a JPA language - JPQL, which lets us write some queries. I, personally, don’t like it. Because of this “some” and because I need to write a String. I loose Java compiler. So let’s look for a complementary tool!
- JPA Repositories, which construct the query from the method name. Simple and useful for building constraining queries over entities.
Hibernate’s basic find() and persist() combined with JPA Repositories, usually cover 70–80% (if not more) of an application database needs. And do it very clean and efficient.
What is left? The complex queries. The business logic that we want to delegate to the database. Stuff, that we usually consult with a DBA about. Probably the most important stuff from business perspective, yet it does not account for more than 20–30% of our database needs.
So, for the remaining 20–30%, are you ready to loose the simplicity of the other 70%? I don’t recommend. Rather, let’s pick a tool that will complement and provide the missing functionality.
Fluent JPA
FluentJPA lets write SQL in Java, using the entities defined with JPA model (mappings). It lets use Java language, with type safety, intellisense, refactoring and other IDE features. With it you can cover the remaining database needs. Let’s see several examples:
There is no limits on what you can do with FluentJPA. But the most important thing is that you can take the best tool for each task without compromising neither on maintainability nor on functionality or performance!