Audit { @PreUpdate @PrePersist public void setAuditFields(Object entity) { final LocalDateTime NOW = now(); for (Field field : entity.getClass().getDeclaredFields()) { if (field.getAnnotation(Auditable.class) != null && field.getType().equals(Date.class)) { try { LOGGER.finest(() -> format("Setting %s field %s to %s", entity.getClass(), field.getName(), NOW)); field.setAccessible(true); field.set(entity, java.sql.Timestamp.valueOf(NOW)); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } }  @PreUpdate @PrePersist void setAuditFields(Object entity);  }
@Test public void the_audit_fields_are_set_if_marked_as_auditable() throws InterruptedException { final Timestamp NOW = Timestamp.from(Instant.now()); AuditableClass auditable = new AuditableClass(); new Audit().setAuditFields(auditable); assertThat(auditable.lastUpdate).isNotNull(); assertThat(auditable.lastUpdate.getTime()).isGreaterThan(NOW.getTime()); }
@Test public void the_audit_skips_fields_that_are_not_auditable() { final LocalDateTime NOW = now(); NonAuditableClass notAuditable = new NonAuditableClass(); notAuditable.lastUpdate = NOW; new Audit().setAuditFields(notAuditable); assertThat(notAuditable.lastUpdate).isNotNull(); assertThat(notAuditable.lastUpdate).isEqualTo(NOW); }
@Test public void the_audit_continues_silently_if_the_fields_are_missing() { new Audit().setAuditFields(""); }