在JPA实体中自动设置createdBy和updatedBy,可以通过使用Spring Boot框架中的AuditorAware接口和@EntityListeners注解实现。
首先,创建一个实现了AuditorAware接口的类,该接口用于提供创建者和更新者的信息。在这个例子中,我们将使用Spring Security来获取当前登录用户的信息。
@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属性。
@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注解将实体监听器类与实体类关联。
@Entity
@EntityListeners(AuditingEntityListener.class)
public class MyEntity extends AbstractEntity {
private String someField;
// getters and setters
}
在这个例子中,我们使用了一个抽象实体类AbstractEntity,该类包含了createdBy和updatedBy属性,以便在所有实体类中使用。
@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属性,无需在每个实体类中手动设置。
领取专属 10元无门槛券
手把手带您无忧上云