简体   繁体   中英

Auditing with spring data jpa and hibernate

I have a spring web application with Spring Boot(v2.3.3) and Spring Data. I have a table assessment that contains the following columns:

  1. Id
  2. Name
  3. Address
  4. Version

My use case is any changes of name and address in the table assessment a new row should be created and the version incremented with the same id.

So basically only when either the address or name are updated a new record should be inserted in the assessment table an example is shown below:

Existing record:

 Id       - 23
 Name     - John
 Address  - Southend
 Version  - 1

For example, the name has been updated to Ryan and there should be two rows as follows:

 Id       - 23
 Name     - John
 Address  - Southend
 Version  - 1

 Id       - 23
 Name     - Ryan
 Address  - Southend
 Version  - 2

So basically any changes in the name and address should be audited in assessment table and the version should be incremented.

I have seen hibernate envers for auditing but a new audit table needs to be created and therefore I cannot insert it in the assessment table and also I don't know how to generate the version number.

I can write the code programmatically to achieve this but is there any other available auditing tool that I can achieve it please?

Thanks in advance

I am not sure what yours expectations. Why you want to use some tool ? Like envers.

The problem is connected with automation and DB so first think is trigger .

Mabye the simplest and best way is write just PostUpdateEventListener .

public class VersionUpdateEventListener
    implements PostUpdateEventListener {
 
@Override
public void onPostUpdate(
        PostUpdateEvent event) {

        /*  
        1. getOldState() and getState() 
        2. check updated values
        3. update version +1 or not
        */

}
...

Or use hibernate @PostUpdate annotation.

I'm sure you'll figure it out an find details in docs/google.

Your main entity should have columns Id, Name, Address (not version). And you should put @Audit over entity. After that, you should generate database table scripts (see, for example, method main in the org.hibernate.tool.hbm2ddl.SchemaExport). You will see in script the main and archive table (with the _aud suffix). It will contain the Id,Name, Address, rev. the rev field is your version. When you change the name to Ryan in the main entity and commit, envers automatically adds a new entry to the archive table.

如果支持触发器,请尝试触发器,因为它将涵盖直接从数据库更新的案例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM