How To Use Hibernate @NaturalId
in SpringBoot
Description: This is a SpringBoot application that maps a natural business key using Hibernate @NaturalId
.
Key points:
- in the entity (e.g.,
Book
), mark the fields (business keys) that should act as natural IDs with@NaturalId
; commonly, there is a single such property, but multiple are suppored as well as here. - for non-mutable ids, mark the columns as
@NaturalId(mutable = false)
and@Column(nullable = false, updatable = false, unique = true, ...)
- for mutable ids, mark the columns as
@NaturalId(mutable = true)
and@Column(nullable = false, updatable = true, unique = true, ...)
- override the
equals()
andhashCode()
using the natural id(s) - define a
@NoRepositoryBean
interface (NaturalRepository
) to define two methods, namedfindBySimpleNaturalId()
andfindByNaturalId()
- provide an implementation for this interface (
NaturalRepositoryImpl
) relying on Hibernate,Session
,bySimpleNaturalId()
andbyNaturalId()
methods - for the entity, write a repository class (e.g., for the
Book
entity writeBookNaturalRepository
) that extends theNaturalRepositoryImpl
and use it for setting the entity class type and the natural id type (when an entity uses more than one natural ID, the type is not relevant anymore, simply set it toSerializable
) - inject this class in your services and call
findBySimpleNaturalId()
orfindByNaturalId()