Auditoria com @CreatedDate
Acompanhe automaticamente a criação e as alterações das entidades.
Auditoria com @CreatedDate é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
What is JPA Auditing
Auditing automatically tracks who created or modified an entity and when, without manual code in every save.
Spring Data JPA fills audit fields on insert and update for you.
Enabling Auditing
Add @EnableJpaAuditing to a configuration class to activate the feature.
@Configuration
@EnableJpaAuditing
public class JpaConfig {
}Registering the Listener
Annotate audited entities with @EntityListeners(AuditingEntityListener.class) so the callbacks fire.
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Product {
@Id @GeneratedValue
private Long id;
}@CreatedDate
@CreatedDate is set once when the entity is first persisted.
@CreatedDate
private Instant createdAt;@LastModifiedDate
@LastModifiedDate updates on every save, including updates.
@LastModifiedDate
private Instant updatedAt;A Complete Audited Entity
Putting the timestamp fields together.
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Product {
@Id @GeneratedValue
private Long id;
@CreatedDate
private Instant createdAt;
@LastModifiedDate
private Instant updatedAt;
}Auditing the User
@CreatedBy and @LastModifiedBy record who made the change.
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;AuditorAware
To populate the user fields, provide an AuditorAware bean that returns the current principal.
@Bean
public AuditorAware<String> auditorProvider() {
return () -> Optional.of(
SecurityContextHolder.getContext()
.getAuthentication().getName());
}Reusable Base Class
Put audit fields in a @MappedSuperclass so all entities inherit them.
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
@CreatedDate
private Instant createdAt;
@LastModifiedDate
private Instant updatedAt;
}Choosing a Date Type
Audit fields can be Instant, LocalDateTime, or Long. Configure the reference via dateTimeProviderRef if needed.
Verifying Auditing
On the first save createdAt and updatedAt are equal; after an update, only updatedAt changes.
Product p = repository.save(new Product());
// createdAt == updatedAt
p.setName("New");
repository.save(p);
// updatedAt is now later than createdAtQuick Check
Test your understanding of auditing.
Recap
You learned automatic auditing:
@EnableJpaAuditingturns it on@EntityListeners(AuditingEntityListener.class)on entities@CreatedDate/@LastModifiedDatefor timestampsAuditorAwarepopulates@CreatedBy
Perguntas Frequentes
A aula “Auditoria com @CreatedDate” é grátis?
Sim — o texto completo de “Auditoria com @CreatedDate” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
O que vou aprender em “Auditoria com @CreatedDate”?
Acompanhe automaticamente a criação e as alterações das entidades. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?
Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Auditoria com @CreatedDate”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?
Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Consultas dinâmicas com especificações
- Projeções e DTOs
- Auditoria com @CreatedDate
- Paginação e ordenação