公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

启动类上加上@EnableJpaAuditing

image.png

实体类,注意需要加上@EntityListeners(AuditingEntityListener.class)这个注解才能使@CreatedDate@LastModifiedDate生效

package com.gecko.charging.partner.entity;

import com.gecko.charging.partner.enums.PartnerType;
import com.gecko.charging.partner.enums.PartnerSettlementMethod;
import com.meenoframework.common.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Table;
import java.util.Date;

/**
 * @description: 合作商
 * @author: Wzq
 * @create: 2020-03-02 14:25
 */
@Entity
@Table(name = "partner")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class Partner extends BaseEntity {

    // 用户id
    private Long userId;

    // 邮箱
    private String email;

    // 公司名称
    private String companyName;

    // 组织机构代码
    private String orgCode;

    //区域id
    private String areaId;

    //详细地址
    @Column(columnDefinition = "TEXT")
    private String address;

    //合作商类型
    @Column(name = "type")
    private PartnerType partnerType;

    //结算方式
    private PartnerSettlementMethod settlementMethod;

    // 营业执照
    private String businessLicense;

    // 小区名称
    private String areaName;

    // 创建时间
    @CreatedDate
    private Date createTime;

    // 创建id
    @CreatedBy
    private Long creatorId;

    // 修改人
    @LastModifiedBy
    private Long updateId;

    // 修改时间
    @LastModifiedDate
    private Date updateTime;

    // 是否删除
    private Integer isDeleted;

}

@CreatedBy@LastModifiedBy使它们生效需要配置转换类实现AuditorAware接口

package com.gecko.charging.partner.repository.auditoraware;

import com.meenoframework.common.filter.ThreadLocalClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;

import java.util.Optional;

/**
 * @description: 合作商创建人和修改人jpa处理
 * @author: Wzq
 * @create: 2020-03-02 14:48
 */
@Configuration
public class PartnerAuditorAware implements AuditorAware<Long> {
    @Override
    public Optional<Long> getCurrentAuditor() {
        //项目中获取登录用户id的方法
        Long currentLoginUserId = ThreadLocalClient.get().getId();
        if(currentLoginUserId != null){
            return Optional.of(currentLoginUserId);
        }
        return Optional.empty();
    }
}


成功!

image.png

posted on 2020-09-18 12:05  公众号/架构师与哈苏  阅读(243)  评论(0编辑  收藏  举报