首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在JPA实体中自动设置createdBy和updatedBy

在JPA实体中自动设置createdBy和updatedBy,可以通过使用Spring Boot框架中的AuditorAware接口和@EntityListeners注解实现。

首先,创建一个实现了AuditorAware接口的类,该接口用于提供创建者和更新者的信息。在这个例子中,我们将使用Spring Security来获取当前登录用户的信息。

代码语言:java
复制
@Component
public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return Optional.empty();
        }
        return Optional.of(((UserDetails) authentication.getPrincipal()).getUsername());
    }
}

接下来,创建一个实体监听器类,用于在实体的创建和更新事件中设置createdBy和updatedBy属性。

代码语言:java
复制
@Component
public class AuditingEntityListener {

    @Autowired
    private AuditorAwareImpl auditorAware;

    @PrePersist
    public void setCreatedBy(Object target) {
        if (target instanceof AbstractEntity) {
            AbstractEntity entity = (AbstractEntity) target;
            if (entity.getCreatedBy() == null) {
                entity.setCreatedBy(auditorAware.getCurrentAuditor().orElse(null));
            }
        }
    }

    @PreUpdate
    public void setUpdatedBy(Object target) {
        if (target instanceof AbstractEntity) {
            AbstractEntity entity = (AbstractEntity) target;
            entity.setUpdatedBy(auditorAware.getCurrentAuditor().orElse(null));
        }
    }
}

最后,在实体类中添加createdBy和updatedBy属性,并使用@EntityListeners注解将实体监听器类与实体类关联。

代码语言:java
复制
@Entity
@EntityListeners(AuditingEntityListener.class)
public class MyEntity extends AbstractEntity {

    private String someField;

    // getters and setters
}

在这个例子中,我们使用了一个抽象实体类AbstractEntity,该类包含了createdBy和updatedBy属性,以便在所有实体类中使用。

代码语言:java
复制
@MappedSuperclass
public abstract class AbstractEntity {

    @Column(name = "created_by", nullable = false, length = 50)
    private String createdBy;

    @Column(name = "updated_by", nullable = false, length = 50)
    private String updatedBy;

    // getters and setters
}

通过这种方式,在JPA实体中可以自动设置createdBy和updatedBy属性,无需在每个实体类中手动设置。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

1分35秒

高速文档自动化系统在供应链管理和物流中的应用

1分51秒

Ranorex Studio简介

18秒

四轴激光焊接示教系统

14分22秒

如何自动化批量输出个性化图片

7分38秒

人工智能:基于强化学习学习汽车驾驶技术

59秒

BOSHIDA DC电源模块在工业自动化中的应用

1分10秒

PS小白教程:如何在Photoshop中制作透明玻璃效果?

1分53秒

安全帽佩戴识别系统

1分28秒

人脸识别安全帽识别系统

1分36秒

SOLIDWORKS Electrical 2023电气设计解决方案全新升级

48秒

DC电源模块在传输过程中如何减少能量的损失

4分36秒

PS小白教程:如何在Photoshop中制作雨天玻璃文字效果?

领券