How to map a composite identifier using an automatically @GeneratedValue with JPA and Hibernate

Introduction

One of my readers asked me to answer the following StackOverflow question.

While I already covered the best way to map composite identifiers with JPA and Hibernate, this use case is different because one column is automatically generated.

Continue reading “How to map a composite identifier using an automatically @GeneratedValue with JPA and Hibernate”

Advertisements

Why you should never use the TABLE identifier generator with JPA and Hibernate

Introduction

From a data access perspective, JPA supports two major types of identifiers:

  • assigned
  • generated

The assigned identifiers must be manually set on every given entity prior to being persisted. For this reason, assigned identifiers are suitable for natural keys.

For synthetic Primary Keys, we need to use a generated entity identifier, which is supported by JPA through the use of the @GeneratedValue annotation.

There are four types of generated identifier strategies which are defined by the GenerationType enumeration:

  • AUTO
  • IDENTITY
  • SEQUENCE
  • TABLE

The AUTO identifier generator strategy chooses one of the other three strategies (IDENTITY, SEQUENCE or TABLE) based on the underlying relational database capabilities.

While IDENTITY maps to an auto-incremented column (e.g. IDENTITY in SQL Server or AUTO_INCREMENT in MySQL) and SEQUENCE is used for delegating the identifier generation to a database sequence, the TABLE generator has no direct implementation in relational databases.

This post is going to analyze why the TABLE generator is a poor choice for every enterprise application that cares for performance and scalability.

Continue reading “Why you should never use the TABLE identifier generator 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)”