Spring Boot @CreatedBy Example

1. Introduction

The @CreatedBy annotation is part of Spring Data JPA and is used for auditing purposes within Spring Boot applications. It automatically populates the annotated field with the creator's identifier when the entity is saved, ideal for tracking who created a specific database entry.

Key Points

1. @CreatedBy helps automatically capture the identifier of the user who created an entity.

2. Implementation requires enabling JPA auditing and a configuration of AuditorAware to fetch the current user.

3. Often integrated with Spring Security to identify the currently logged-in user.

2. Program Steps

1. Enable JPA Auditing in your configuration.

2. Implement the AuditorAware interface to return the current auditor.

3. Annotate the creator field in your entity with @CreatedBy.

4. Optionally, integrate with Spring Security for real user identification.

3. Code Program

// Step 1: Enable JPA Auditing
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class AuditConfig {
}

// Step 2: Implement the AuditorAware interface
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
import java.util.Optional;

@Component("auditorProvider")
public class AuditorAwareImpl implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        // This example uses a hardcoded username, replace it with dynamic user retrieval logic
        return Optional.of("Ramesh");
    }
}

// Step 3: Define an entity with @CreatedBy
import jakarta.persistence.*;
import org.springframework.data.annotation.CreatedBy;

@Entity
public class AuditEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @CreatedBy
    private String createdBy;

    // Getters and Setters
}

// Step 4: Repository interface
import org.springframework.data.jpa.repository.JpaRepository;

public interface AuditEntityRepository extends JpaRepository<AuditEntity, Long> {
}

Explanation:

1. AuditConfig configures JPA auditing and specifies auditorProvider as the bean that determines the current auditor.

2. AuditorAwareImpl provides the logic to determine the current auditor's username. Here it's hardcoded as "Ramesh", which should be replaced with the logic to fetch the actual username, potentially from Spring Security's authentication context.

3. The AuditEntity class has a field createdBy annotated with @CreatedBy, which will be automatically populated by Spring Data JPA based on the result from AuditorAwareImpl.

4. AuditEntityRepository extends JpaRepository, providing all CRUD operations, including automatic handling of the @CreatedBy field when entities are persisted.

Comments