Spring Data JPA Auditing Example – SpringBoot RestAPIs + MySQL

spring-jpa-auditing-spring-data-mysql-feature-image

In the tutorial, we show how to build a SpringBoot application with a Database Auditing feature for tracking the change (with 2 fields created_at & updated_at) by using Spring Data JPA, Java 8 DateTime, and MySQL.

Related posts:
How to use Spring JPA MySQL | Spring Boot
Spring JPA Hibernate One to Many Relationship – SpringBoot + MySQL

Technologies

– Java 8
– SpringBoot 2.0.6.RELEASE
– MySQL

Goal

We create a SpringBoot project as below structure:

spring-jpa-auditing-spring-data-mysql-project-structure

Run & Check results:

-> Post request:

spring-jpa-auditing-spring-data-mysql-post-customer

spring-jpa-auditing-spring-data-mysql-after-posts-database

-> Put request:

spring-jpa-auditing-spring-data-mysql-put-customer

spring-jpa-auditing-spring-data-mysql-put-customer-check-record

With 2 fields created_at & updated_at, we can track the change of database’s records.

How to achieve it? -> We use Spring JPA Auditing.
– Firstly, configure JPA Auditing:

– Then we create a DateAudit class as below:

– Domain class Customer need inherit from DateAudit class:

Pratice

Create SpringBoot project

– We create a SpringBoot project with below dependencies:

jackson-datatype-jsr310 is used to support Java 8 Date/Time.

JPA Audit Implementation

– Configure JPA Auditing:

– Implement DateAudit ->

@EntityListeners annotation is used to specify callback listener classes. We use the JPA entity listener class of Spring Data AuditingEntityListener.
@MappedSuperClass annotation is used to move the properties to a base class DateAudit which would be extended by all your audited entities.

Create Model class

– Create JsonView Customer class:

– Create Customer model class:

@JsonView annotation of Jackson library is used to serialize/de-serialize Java objects and customize the fields of JSON view.

-> See more at: How to use @JsonView to serialize/de-serialize and customize JSON format from Java Object

Create JPA Repository

CustomerRepository.java ->

RestAPIs Controller Implementation

CustomerRestAPIs.java ->

Main Class Implementation

– Set the default timezone for our application to UTC.

Application Configuration

application.properties ->

Run & Check results

Start SpringBoot project,

-> MySQL table:

spring-jpa-auditing-spring-data-mysql-start-project-table-schema

– Post customers ->

spring-jpa-auditing-spring-data-mysql-post-customer

spring-jpa-auditing-spring-data-mysql-after-posts-database

– Update customer ->

spring-jpa-auditing-spring-data-mysql-put-customer

spring-jpa-auditing-spring-data-mysql-put-customer-check-record

– Get customers ->

spring-jpa-auditing-spring-data-mysql-get-all-customer

SourceCode

SpringBootJpaAudit

By grokonez | October 30, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*