In the world of Spring Boot development, efficient data management is crucial for application performance and maintainability. One powerful feature offered by Spring Data JPA is the ability to automatically track the creation and modification timestamps of entities. In this guide, we’ll dive into the usage of two key annotations, @CreatedDate
and @LastModifiedDate
along with @EntityListeners
to auto generate created and modified date time in Spring Boot applications.
Table of Contents
Understanding the Annotations
The @CreatedDate
and @LastModifiedDate
annotations are part of Spring Data JPA’s auditing capabilities. By incorporating these annotations into our entity classes, we can automate the recording of creation and modification timestamps without the need for manual intervention.
Entity Class
We need to annotate our entity class with @EntityListeners
and extend AuditingEntityListener
. Also, we need to use @CreatedDate
and @LastModifiedDate
annotations for the date-time fields.
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@EntityListeners(AuditingEntityListener.class)
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Other fields...
@CreatedDate
@Column(name = "created_at")
private LocalDateTime createdAt;
@LastModifiedDate
@Column(name = "updated_at")
private LocalDateTime updatedAt;
// Getters and setters...
}
Enable Autiding
Enable auditing in our Spring Boot application by adding the @EnableJpaAuditing
annotation. I prefer to use this annonation in the main class. If you want to use it in custom configuration then you can.
Example:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
public class SBApplication {
public static void main(String[] args) {
SpringApplication.run(BanyanServiceApplication.class, args);
}
}
That’s it 🙂
With these annotations and configuration, Spring Data JPA will automatically update the createdAt
and updatedAt
fields in our entity class.