How to audit entity modifications using the JPA @EntityListeners, @Embedded, and @Embeddable annotations

Introduction

After I wrote the article about inheriting properties from a base class entity using @MappedSuperclass, I got an avalanche of opinions, but this one from Lukas deserves a blog post:

While @MappedSuperclass has its benefit, allowing you to reuse even the @Id mapping, as well as being more lenient towards Hibernate-specific auto-generated properties like @GeneratedValue, using Embeddable types is the other JPA alternative for reusing a bunch of properties among multiple entities.

In this article, we are going to see how we can reuse several audit-related properties using @Embeddable and another awesome JPA feature, @EntityListeners.

Continue reading “How to audit entity modifications using the JPA @EntityListeners, @Embedded, and @Embeddable annotations”

Advertisements

The best way to map a many-to-many association with extra columns when using JPA and Hibernate

Introduction

For a simple many-to-many database relationship, you can use the @ManyToMany JPA annotation and, therefore, hide the join table.

However, sometimes you need more than the two Foreign Key columns in the join table, and, for this purpose, you need to replace the @ManyToMany association with two bidirectional @OneToMany associations. Unlike unidirectional @OneToMany, the bidirectional relationship is the best way to map a one-to-many database relationship that requires a collection of Child elements on the parent side

In this article, we are going to see how you can map a many-to-many database relationship using an intermediary entity for the join table. This way, we can map additional columns that would be otherwise impossible to persist using the @ManyToMany JPA annotation.

Continue reading “The best way to map a many-to-many association with extra columns when using JPA and Hibernate”