Spring Boot @CreatedBy Example

1. Introduction

In a Spring Boot application, auditing is an essential aspect of persisting entity data, such as keeping track of who created or modified an entity and when this happened. The Spring Data JPA @CreatedBy annotation is an essential tool for capturing the user who created a particular entity. This blog post will provide an example of how to use the @CreatedBy annotation within a Spring Boot application.

Key Points:

1. @CreatedBy is used to automatically capture the user who created the entity.

2. It works with Spring Security to retrieve the currently authenticated user.

3. This annotation is part of the Spring Data Auditing feature, which needs to be explicitly enabled in the configuration.

4. @CreatedBy can be used alongside other annotations like @LastModifiedBy, @CreatedDate, and @LastModifiedDate to provide a full auditing solution.

5. To capture the user information, you need to provide an AuditorAware implementation that tells Spring Data who the current user or auditor is.

2. Implementation Steps

1. Add Spring Data JPA and Spring Security dependencies to your project.

2. Configure your security to authenticate users.

3. Create an entity that includes a field for the creator.

4. Annotate this field with @CreatedBy.

5. Enable JPA Auditing in your configuration.

6. Provide an AuditorAware implementation to supply the current auditor.

7. Use the entity in your application and see how Spring fills in the @CreatedBy field automatically.

3. Implementation Example

// Step 1: Create an entity class and use the @CreatedBy annotation
@Entity
public class Note {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String content;

    @CreatedBy
    private String createdBy;

    // Standard getters and setters
}

// Step 2: Create an AuditorAware implementation
@Component
public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        // For simplicity, we're returning a fixed username. In a real application, you would return the authenticated user's name.
        return Optional.of("Prabhas");
    }
}

// Step 3: Enable JPA Auditing in your configuration class
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAwareImpl")
public class PersistenceConfig {
    // Other configurations
}

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

// Step 5: Use the repository in a service class
@Service
public class NoteService {
    private final NoteRepository noteRepository;

    @Autowired
    public NoteService(NoteRepository noteRepository) {
        this.noteRepository = noteRepository;
    }

    public Note createNote(String content) {
        Note note = new Note();
        note.setContent(content);
        return noteRepository.save(note);
    }
}

// Step 6: Optionally, create a REST Controller to expose the functionality to create a note
@RestController
@RequestMapping("/api/notes")
public class NoteController {
    private final NoteService noteService;

    @Autowired
    public NoteController(NoteService noteService) {
        this.noteService = noteService;
    }

    @PostMapping
    public Note createNote(@RequestBody Note note) {
        return noteService.createNote(note.getContent());
    }
}

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

// After running the application, creating a note via the REST endpoint will automatically fill in the createdBy field.

Output:

// When a note is created through the POST /api/notes endpoint with the request body:
{
    "content": "This is a sample note."
}
// The response will include the createdBy field set to "Prabhas":
{ "id": 1, "content": "This is a sample note.", "createdBy": "Prabhas"
}

Explanation:

1. Note: The JPA entity class that includes the createdBy field to store information about the entity creator.

2. @CreatedBy: This annotation is used on the createdBy field to indicate that it should be automatically populated with the current auditor's name when the entity is created.

3. AuditorAwareImpl: The implementation of the AuditorAware interface to provide the current auditor's information.

4. @EnableJpaAuditing: This annotation is added to a @Configuration class to enable auditing in JPA.

5. NoteRepository: The Spring Data JPA repository interface for CRUD operations on Note entities.

6. NoteService: A service class that handles the business logic for note operations.

7. @Service: Indicates that NoteService is a Spring-managed service bean.

8. NoteController: A REST controller that provides an HTTP API for creating notes.

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

10. @PostMapping: Maps HTTP POST requests to the createNote method.

11. @RequestBody: Indicates that a method parameter should be bound to the body of the web request.

12. CreatedByAnnotationExampleApplication: The main application class is marked with @SpringBootApplication.

13. SpringApplication.run(): Launches the Spring Boot application.


Comments