hibernate不同實體不同填充建立人

zengli11發表於2024-08-01

hibernate不同實體不同填充建立人

使用的el-admin框架,框架本身填充的使用@CreatedBy註解加上AuditingEntityListener,

@CreatedBy
@Column(name = "create_by", updatable = false)
@ApiModelProperty(value = "建立人", hidden = true)
private String createBy;


@Component("auditorAware")
public class AuditorConfig implements AuditorAware<String> {

    /**
     * 返回操作員標誌資訊
     *
     * @return /
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        try {
            // 這裡應根據實際業務情況獲取具體資訊
            return Optional.of(SecurityUtils.getCurrentUsername());
        }catch (Exception ignored){}
        // 使用者定時任務,或者無Token呼叫的情況
        return Optional.of("System");
    }
}

但是我的專案createBy是Long型別,所以需要不同的填充方式

實體基類

@EntityListeners(CustomAuditingListener.class)
@javax.persistence.MappedSuperclass
@Data
@Accessors(chain = true)
public class BaseEntity implements Serializable {

	/**
	 * 建立人id
	 */
	@Column(name = "create_id")
	protected Long createId;

}

主要是加入 @EntityListeners(CustomAuditingListener.class)

實現CustomAuditingListener

@Configurable
public class CustomAuditingListener implements ConfigurableObject {

    public CustomAuditingListener() {
    }

    @Autowired
    private AuditHandler auditHandler;

    @PrePersist
    private void prePersist(Object obj) {
        auditHandler.prePersist(obj);
    }
    @PreUpdate
    private void preUpdate(Object obj) {
        auditHandler.preUpdate(obj);
    }
}

AuditHandler介面

public interface AuditHandler {
    void prePersist(Object obj);

    void preUpdate(Object obj);
}


@Component
public class CustomAuditHandler implements AuditHandler {

    @Override
    public void prePersist(Object obj) {
        if (obj instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) obj;
            if (entity.getCreateId() == null) {
                this.markForCreate(entity);
            }
            entity.setCreateTime(new Date());
            entity.setDataStatus(1);
        }
    }

    @Override
    public void preUpdate(Object obj) {
        if (obj instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) obj;
            if(entity.getUpdateId() == null){
                this.markForUpdate(entity);
            }
            entity.setUpdateTime(new Date());
            entity.setDataStatus(1);
        }
    }

    public void markForCreate(BaseEntity entity) {
        Long userId = getLoginUserId();
        entity.setCreateId(userId);
    }

    public void markForUpdate(BaseEntity entity) {
        // TODO 問題 https://stackoverflow.com/questions/54041338/stackoverflow-on-preupdate
        Long userId = getLoginUserId();
        entity.setUpdateId(userId);
    }

    private static Long getLoginUserId() {
        JwtUserDto userCache = SpringUtil.getBean(UserCacheManager.class).getUserCache(SecurityUtils.getCurrentUsername());
        Long userId = Optional.ofNullable(userCache).map(e -> e.getUser()).map(e -> e.getId()).orElse(null);
        return userId;
    }
}

相關文章