How to map calculated properties with JPA and Hibernate @Formula annotation

Introduction

As I explained in this StackOverflow question, mapping calculated properties is very easy with JPA and Hibernate.

In this post, I’m going to demonstrate how you can derive some entity property based on one or multiple persistent entity attributes.

Continue reading “How to map calculated properties with JPA and Hibernate @Formula annotation”

The best way to lazy load entity attributes using JPA and Hibernate

Introduction

When fetching an entity, all attributes are going to be loaded as well. This is because every entity attribute is implicitly marked with the @Basic annotation whose default fetch policy is FetchType.EAGER.

However, the attribute fetch strategy can be set to FetchType.LAZY, in which case the entity attribute is loaded with a secondary select statement upon being accessed for the first time.

@Basic(fetch = FetchType.LAZY)

This configuration alone is not sufficient because Hibernate requires bytecode instrumentation to intercept the attribute access request and issue the secondary select statement on demand.

Continue reading “The best way to lazy load entity attributes using JPA and Hibernate”

Fluent API entity building with JPA and Hibernate

Introduction

The JHipster development team wants to expose Fluent Interface entity building methods for their JPA entities, so they asked me if this is going to work with JPA and Hibernate. While JPA is rather strict about entity getters and setter, Hibernate is more lenient in this regard.

Continue reading “Fluent API entity building with JPA and Hibernate”

How to implement equals and hashCode using the JPA entity identifier (primary key)

Introduction

As previously explained, using the JPA entity business key for equals and hashCode is always best choice. However, not all entities feature a unique business key, so we need to use another database column that is also unique, like the primary key.

But using the entity identifier for equality is very challenging, and this post is going to show you how you can use it without issues.

Continue reading “How to implement equals and hashCode using the JPA entity identifier (primary key)”