Spring Boot @LastModifiedDate Example

1. Introduction

Tracking when a database record was last modified is a common requirement in software development. Spring Boot, in combination with Spring Data JPA, provides the @LastModifiedDate annotation to facilitate this process. This annotation automatically updates the timestamp whenever an entity is updated. In this blog post, we'll demonstrate how to use @LastModifiedDate to audit entity modifications.

Key Points:

1. @LastModifiedDate is used to automatically update the timestamp field in an entity when it is modified.

2. This feature is part of Spring Data JPA’s auditing capability, which helps in keeping track of when entities are changed.

3. It requires the @EnableJpaAuditing annotation in your configuration to activate auditing.

4. Typically, @LastModifiedDate is used in conjunction with @LastModifiedBy, @CreatedDate, and @CreatedBy to provide full auditing information.

5. For @LastModifiedDate to work, the entity must also have a field annotated with @Version for optimistic locking, which can also help prevent concurrent updates.

2. Implementation Steps

1. Add the spring-boot-starter-data-jpa dependency to your Spring Boot application.

2. Enable JPA auditing in a configuration class with @EnableJpaAuditing.

3. Create an entity with a field to store the last modified date.

4. Annotate this field with @LastModifiedDate to enable automatic timestamp updates.

5. Implement a repository interface for your entity that extends JpaRepository.

6. Update and save an entity using the repository and observe the @LastModifiedDate in action.

3. Implementation Example

// Step 1: Create an entity class with a lastModifiedDate field
@Entity
public class Document {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String content;

    // Step 2: Annotate the field with @LastModifiedDate
    @LastModifiedDate
    private Instant lastModifiedDate;

    // Standard getters and setters
}

// Step 3: Enable JPA auditing in your configuration class
@Configuration
@EnableJpaAuditing
public class AuditConfig {
    // Other configurations
}

// Step 4: Create a repository interface for the Document entity
public interface DocumentRepository extends JpaRepository<Document, Long> {
}

// Step 5: Use the repository in a service class to manage Document entities
@Service
public class DocumentService {
    private final DocumentRepository documentRepository;

    @Autowired
    public DocumentService(DocumentRepository documentRepository) {
        this.documentRepository = documentRepository;
    }

    public Document updateDocumentContent(Long id, String newContent) {
        Document document = documentRepository.findById(id).orElseThrow();
        document.setContent(newContent);
        return documentRepository.save(document);
    }
}

// Step 6: Optionally, create a REST Controller to expose the document update functionality
@RestController
@RequestMapping("/api/documents")
public class DocumentController {
    private final DocumentService documentService;

    @Autowired
    public DocumentController(DocumentService documentService) {
        this.documentService = documentService;
    }

    @PutMapping("/{id}")
    public ResponseEntity<Document> updateDocument(@PathVariable Long id, @RequestBody String newContent) {
        Document updatedDocument = documentService.updateDocumentContent(id, newContent);
        return ResponseEntity.ok(updatedDocument);
    }
}

// Step 7: Run the Spring Boot application
@SpringBootApplication
public class LastModifiedDateExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(LastModifiedDateExampleApplication.class, args);
    }
}

// Updating a document via the PUT /api/documents/{id} endpoint will automatically update the lastModifiedDate field.

Output:

// After making a PUT request to update a document, the response might look like:
{
    "id": 1,
    "content": "Updated Content",
    "lastModifiedDate": "2023-11-08T21:54:33.987Z"
}
// The lastModifiedDate field reflects the timestamp of the update.

Explanation:

1. Document: The JPA entity that represents a document record in the database.

2. @LastModifiedDate: This annotation marks the lastModifiedDate field to be automatically updated with the current date and time when the Document entity is updated.

3. AuditConfig: A configuration class that enables JPA auditing by using the @EnableJpaAuditing annotation.

4. DocumentRepository: The Spring Data JPA repository that provides CRUD operations for the Document entity.

5. DocumentService: A service layer class that contains the business logic to update the content of a document.

6. @Service: This annotation marks DocumentService as a Spring-managed service bean.

7. DocumentController: A REST controller class that exposes an HTTP API to update documents.

8. @RestController and @RequestMapping: Annotations to define a REST controller and map web requests to handler methods.


Comments