top of page
Search
Writer's pictureLeonard Anghel

How To Use Hibernate Attribute Lazy Loading

Updated: May 10, 2020

Motivation:

From performance perspective, we must avoid loading from the database more data than needed. Attribute lazy loading is a technique that allows us to load only the needed attributes. This is especially useful for avoiding loading uncessary heavy attirbutes (CLOB, BLOB, VARBINARY, and so on). Unfortunately, in Spring Boot, it is not that straightforward to accomplishing it.


150+ PERSISTENCE PERFORMANCE ITEMS

THAT WILL ROCK YOUR APPS


Description:

By default, the attributes of an entity are always loaded eagerly (all at once).

But, we can load them lazily as well. This is useful for column types that store large amounts of data: CLOB, BLOB, VARBINARY, etc or details that should be loaded on demand.

In this application, we have an entity named Author. Its properties are id, name, genre, avatar and age. And, we want to load the id, name and genre eagerly, while avatar should be loaded lazily. So, the avatar should be loaded on demand.


Key points:

  • In pom.xml, activate Hibernate Bytecode Enhancement (e.g. use Maven Bytecode Enhancement plugin):

  • In the entity (Author), annotate the attributes that should be loaded lazily with @Basic(fetch = FetchType.LAZY). In our case, we annotate avatar:

  • In application.properties, disable Open Session in View:

Testing time:

Now, we can test it from a service-method as follows:

Most probably you'll need to read the following two articles as well:


Tam Ta Da Dam! :) The complete application is available on GitHub.


If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices".


1,419 views0 comments

Recent Posts

See All

How To Bulk Updates

Motivation: This article is useful if you need a fast way to update a significant amount of data in the database. Bulk operations...

Kommentare


bottom of page