SpringData JPA 之 Auditing 自动填充字段

905人浏览 / 0人评论

启动类

@EnableJpaAuditing(auditorAwareRef = "auditorAware")

AuditorConfig.class

import io.undertow.util.BadRequestException;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component("auditorAware")
public class AuditorConfig implements AuditorAware<String> {
    /**
     * 返回操作员标志信息
     *
     * @return /
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        try {
            // 这里应根据实际业务情况获取具体信息
            return Optional.of(getUserName());
        } catch (Exception ignored) {
        }
        // 用户定时任务,或者无Token调用的情况
        return Optional.of("System");
    }
    public String getUserName() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null) {
            return principal.toString();
        } else {
            return "anonymousUser";
        }
    }
    /**
     * 获取系统用户名称(有问题)
     *
     * @return 系统用户名称
     */
    public static String getCurrentUsername() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            try {
                throw new BadRequestException("当前登录状态过期");
            } catch (BadRequestException e) {
                e.printStackTrace();
            }
        }
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return userDetails.getUsername();
        }
        try {
            throw new BadRequestException("找不到当前登录的信息");
        } catch (BadRequestException e) {
            return "anonymousUser";
        }
    }
}

BaseEntity.class

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Timestamp;
/**
 * @Author 风仔
 * @Date 2022/5/25
 * @Version 1.0
 * @Description:	数据库中要有对应的字段
 **/
@Getter
@Setter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity implements Serializable {

    @CreatedBy
    @Column(name = "create_by", updatable = false)
    @ApiModelProperty(value = "创建人", hidden = true)
    private String createBy;
    
    @LastModifiedBy
    @Column(name = "update_by")
    @ApiModelProperty(value = "更新人", hidden = true)
    private String updateBy;
    
    @CreationTimestamp
    @Column(name = "create_time", updatable = false)
    @ApiModelProperty(value = "创建时间", hidden = true)
    private Timestamp createTime;
    
    @UpdateTimestamp
    @Column(name = "update_time")
    @ApiModelProperty(value = "更新时间", hidden = true)
    private Timestamp updateTime;
    
    /* 分组校验 */
    public @interface Create {}
    
    /* 分组校验 */
    public @interface Update {}
    
    @Override
    public String toString() {
        ToStringBuilder builder = new ToStringBuilder(this);
        Field[] fields = this.getClass().getDeclaredFields();
        try {
            for (Field f : fields) {
                f.setAccessible(true);
                builder.append(f.getName(), f.get(this)).append("\n");
            }
        } catch (Exception e) {
            builder.append("toString builder encounter an error");
        }
        return builder.toString();
    }
}

使用示例

import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
/**
 * @Author 风仔
 * @Date 2022/5/9
 * @Version 1.0
 * @Description:
 **/
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "organization")
@ApiModel("组织实体")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Organization extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;
    @Column(name = "dam_id")
    private Integer damId;
    @Column(name = "name")
    private String name;
    @Column(name = "duty")
    private String duty;
    @Column(name = "type")
    private Integer type;
}

全部评论