A Guide to Implementing Auditing with JPA and Generators
1. Overview
Auditability refers to the ability to track and record changes made to data in a database over time. This process involves keeping track of information such as who made the changes and when they were made. By tracking this information, it becomes possible to audit the changes and identify any unauthorized or unexpected modifications.
In the context of a database table, auaudibilityypically involves keeping track of the creation and updates of individual rows in the table. This can include information such as the user who created the row, the timestamp of when it was created, and any subsequent updates made to the row along with their corresponding timestamps and user information.
Overall, implementing audiaudibility helps organizations maintain data integrity, comply with regulatory requirements, and provide transparency into data changes made by different users over time.
2. Hands-on Coding
2.1 User Holder
public class LoggedUser { private static final ThreadLocal<String> userHolder = new ThreadLocal<>(); public static void logIn(String user) { userHolder.set(user); } public static void logOut() { userHolder.remove(); } public static String get() { return userHolder.get(); } } // How to use this REST. Make sure to get the principal information @Provider public class LoggedUserFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { LoggedUser.logIn("CRUD"); } }
2.2 User Generator
import org.hibernate.Session; import org.hibernate.tuple.ValueGenerator; public class LoggedUserGenerator implements ValueGenerator<String> { @Override public String generateValue(Session session, Object owner) { return LoggedUser.get(); } }
2.3 Auditable Entity
@Data @SuperBuilder @MappedSuperclass @NoArgsConstructor public abstract class AuditableEntity extends BaseEntity { @CreationTimestamp @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt; @UpdateTimestamp @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt; @GeneratorType( type = LoggedUserGenerator.class, when = GenerationTime.INSERT ) @Column(name = "created_by") private String createdBy; @GeneratorType( type = LoggedUserGenerator.class, when = GenerationTime.ALWAYS ) @Column(name = "updated_by") private String updatedBy; }
Post a Comment