Hibernate Auditing – Base Entity and Example Entity

Add Hibernate envers dependency to your pom.xml file :

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-envers</artifactId>
   <version>${hibernate.version}</version>
</dependency>

This is base entity class for enabling auditing :

@MappedSuperclass
@Audited
@Data
public class BaseEntity implements Serializable{

    private static final long serialVersionUID = -1591130256151148932L;

    @CreatedBy
    @Column(nullable = false,length = 50,updatable = false)
    private String createdBy;

    @CreatedDate
    @Column(nullable = false)
    private Instant createdDate = Instant.now();

    @LastModifiedBy
    @Column(length = 50)
    private String updatedBy;

    @LastModifiedDate
    private Instant updatedDate = Instant.now();
}

Example User entity extends BaseEntity :

@Data
@Entity
@EqualsAndHashCode(callSuper=false)
public class User extends BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(length = 100,unique = true,nullable = false)
    private String login;

    private String password;
    private String firstName;
    private String lastName;
    private boolean active = false;
    @Email
    private String email;

    @ManyToMany
    @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
    private Set<Role> roles = new HashSet<>();
}

If a relationship entity in your entity is not audited, then you should add annotation  :
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)

For adding for example “ZLOG_” prefix to your audit tables in your spring boot application.yml file :

spring:
  jpa:
    properties:
      org.hibernate.envers.audit_table_prefix: ZLOG_
Advertisements