top of page
Search
Writer's pictureLeonard Anghel

How To Set Default Values For Lazy Loaded Attributes

Updated: May 10, 2020

Motivation:

From performance perspective, we must avoid loading from the database more data than needed. Attribute lazy loading allows us to load only the needed attributes. This is especially useful for avoiding loading uncessary heavy attirbutes (CLOB, BLOB, VARBINARY, and so on).


150+ PERSISTENCE PERFORMANCE ITEMS

THAT WILL ROCK YOUR APPS


Description:

By default, the attributes of an entity are 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 avatar lazily. But, returning entities (converted as JSON) that contain un-fetched lazy attributes from a REST controller (@RestController) will cause lazy initialization exceptions because Jackson tries to force the fetching of these attributes outside a Hibernate session.


If you don't want to rely on Attribute Lazy Loading And Jackson Serialization then you can quicky use default values for the un-fetched attributes.


For example, if the fetched author is younger than 40 years, we will load the avatar as well. Otherwise, we explicitly set the avatar as null (this is like the default value).


Key points:

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

  • In entity, annotate the attributes that should be loaded lazy with @Basic(fetch = FetchType.LAZY)

  • Annotate the Author with @JsonInclude(Include.NON_DEFAULT) to avoid the serialization of fields with default values (e.g., useful when we set avatar to null):

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

  • In the service-method set decide to load the avatar or to set it to a default value:


Run the following requests (via BookstoreController):

  • fetch an author with the avatar set to null: localhost:8080/author/1

  • fetch an author with the avatar lazy loaded: localhost:8080/author/2


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".



578 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...

Comments


bottom of page