Monday, July 1, 2019

How to keep track the changes to JPA in Spring Boot?

We develop the LOB software of different domain and almost every app use backend database to persist the data. In Java, JPA is widely use for ORM layer in between of app and database. In many occasions, CRUD logging is part of the basic requirement.
One common scenario is application needs to keep track of price change on a particular stock item within a year. It start with $25 initially and increase to $30 in a month. After 3 months, it goes down a little bit to $28 due to excess supply. In following month, it goes back to $30 thanks to higher demand and etc.
Most probably, this kind of information is useful for the end-users and our application needs to support this.
Of course, we can implement this feature by hard-coding each updates to the database, can't we ???
But, we have better option with JPA Entity Listeners. We can easily bind the event listener and persist each changes to database. It is simple and easy to implement with the help of Spring Boot.
Create a new Spring Boot application. Assume we have the following in application.properties file.
spring.datasource.url = jdbc:mysql://localhost:3306/jpa-logger?useSSL=false
spring.datasource.username = test
spring.datasource.password = test
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = create
Detail implementation is as followed.
This is REST controller which is for testing JPA logging feature

AutowireUtil class is used to auto-wire spring-beans inside JPA listener

This is the base class for all model which require the JPA logging for CRUD action.

This is Employee class which inherit from BaseModel.

This is the meta information of CRUD event to be logged into database.

This is the listener class which persist the CRUD meta information into database.

This class inject auto-wire the bean for listener.

EmployeeRepository.java

EventRepository.java

3 comments:

  1. Java is the most widely used programming language. It is designed for the distributed environment of the Internet. Java is freely accessible to users, and we can run it on all the platforms. Java follows the WORA (Write Once, Run Anywhere) principle, and is platform-independent. best spring data jpa courses

    ReplyDelete
  2. Tracking changes in JPA (Java Persistence API) involves utilizing mechanisms like Hibernate's @Audited annotation or event listeners. Sites Proxy Torrenting These capture and persist changes to entities, creating an audit trail.

    ReplyDelete

Image compression using C#

Sometimes, we need to compress the image files while maintaining the image quality. This can be achieved by the following C# implementation....