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.

Domain Model

Assuming we have the following tables in our relational database:

As you can see from the diagram above, all tables share the same four audit-based columns:

created_by

created_on

updated_by

updated_on

Therefore, we want to encapsulate these four entity properties in a reusable @Embedabble type:

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

As demonstrated, JPA allows you to provide entity event listeners which you can register via the @EntityListeners annotation. This way, we can encapsulate the audit-based properties in an @Embeddable type and make it available to multiple entities using the @Embedded annotation.

This way, you can reuse both the data structures (e.g. @Embeddable) and behavior as well (e.g. @EntityListeners).

Subscribe to our Newsletter

* indicates required

Email Address *

10 000readers have found this blog worth following!

If you subscribeto my newsletter, you'll get:

A free sampleof my Video Course about running Integration tests at warp-speed using Docker and tmpfs

For sure, that was a great solution when I have more fields than the common spring-data-jpa audit solution.
And works well here in my case when I have 6 audit columns on creation, but I’ve seen a problem on @PreUpdate where the object Embeddable is changed but when performed the update the field is not updated.

Only when I created a whole new instance of the audit class all fields are changed. What could I do to change only the updatedOn feald?