One of the biggest misconceptions about #Hibernate is that it causes performance problems. But that’s not the case. Many successful projects use it to implement a highly scalable persistence layer.
Here are 8 recommendations for a fast persistence layer
1. Activate statistics to find problems as early as possible
Set the property 𝘩𝘪𝘣𝘦𝘳𝘯𝘢𝘵𝘦.𝘨𝘦𝘯𝘦𝘳𝘢𝘵𝘦_𝘴𝘵𝘢𝘵𝘪𝘴𝘵𝘪𝘤𝘴 to 𝘵𝘳𝘶𝘦 to activate #Hibernate's statistics and get a summary of all performed operations
2. Improve slow queries
You will find slow queries. They are not a Hibernate issue. They occur with every framework, even plain #SQL over JDBC. That’s why your database provides tools to analyze SQL statements.
Optimize your query and execute it as a native statement.
3. Use FetchType.LAZY
To-many associations use FetchType.LAZY by default, and you shouldn't change that.
But you need to change it for your to-one associations. You can do that by setting the fetch attribute on the @ManyToOne or @OneToOne annotation.
@manytoone @OneToOne 4. Use query-specific fetching
If you let #Hibernate initialize lazily fetched associations, it has to use a separate query for each entity and association. That causes n+1 select problems.
Use JOIN FETCH clauses and EntityGraphs to avoid that
@manytoone @OneToOne 5. Model Many-to-Many as Set
#Hibernate manages many-to-many associations inefficiently if you model them as a List. If you add or remove an element, it removes all association records before it inserts all remaining ones.
You can avoid that by modeling it as a java.util.Set
@manytoone @OneToOne 6. Let the database handle data-heavy operations
Databases are optimized to handle huge datasets. Use functions and stored procedures to perform data-heavy operations that are not too complex and only return a small result
@manytoone @OneToOne 7. Use caches
Hibernate offers 3 caches:
1st level cache = all entities used in the current Session
2nd level cache = Session-independent cache that contains entities
Query cache = Session-independent cache that contains query results
@manytoone @OneToOne 8. Perform updates and deletes in bulks
Changing one entity after the other feels natural in Java, but is also inefficient. A better approach would be to use 1 update or delete statement that affect multiple records at once.
You can do this via JPQL, SQL and Criteria API.
@manytoone @OneToOne I explained all tips in more details in this blog post:
thorben-janssen.com/tips-to-boost-…
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.