Spring Data Jpa Listener事件的扩展之自定义EntityListener

Spring Data Jpa Listener事件的扩展之自定义EntityListener

Laughing
2021-07-22 / 0 评论 / 1,300 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年03月17日,已超过307天没有更新,若内容或图片失效,请留言反馈。

随着DDD的设计模式逐渐被大家认可和热捧。JPA通过Listener这种机制可以很好地实现事件分离、状体分离。假如,订单的状态变化
可能对我们来说比较重要,我们需要定一个类去监听订单状态变更,通知相应的逻辑代码各自去干各自的活。

新增一个UserAuditListener类,在相应的操作上添加Callbacks注解

@Slf4j
public class UserAuditListener {

    @PostPersist
    private void postPersist(SysUser sysUser) {
        recordLog(sysUser, OperateType.CREATE);
    }

    @PostRemove
    private void postRemove(SysUser sysUser) {
        recordLog(sysUser, OperateType.REMOVE);
    }

    @PostUpdate
    private void postUpdate(SysUser sysUser) {
        recordLog(sysUser, OperateType.UPDATE);
    }

    @PostLoad
    public void postLoad(SysUser sysUser) {
        recordLog(sysUser, OperateType.LOAD);
    }

    /**
     * 记录审计日志
     *
     * @param sysUser     用户实体
     * @param operateType 操作类型
     */
    private void recordLog(SysUser sysUser, OperateType operateType) {
        log.info("{}执行了{}操作", sysUser, operateType.getType());
    }

}

enum OperateType {

    CREATE("创建"), UPDATE("更新"), REMOVE("删除"), LOAD("查询");

    private final String type;

    OperateType(String type) {
        this.type = type;
    }

    public String getType() {
        return this.type;
    }
}

修改实体,增加@EntityListeners注解

@Entity
@Table(name = "sys_user")
@Data
@Slf4j

@EntityListeners({UserAuditListener.class})
public class SysUser extends AbstractAuditable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @JoinColumn(name = "dept_id", referencedColumnName = "dept_id")
    @ManyToOne(cascade = CascadeType.ALL)
    private SysDept sysDept;

    private String userName;

    private String nickName;

    private String userType;

    private String email;

    @Column(name = "phonenumber")
    private String phoneNumber;

    private String sex;

    private String avatar;

    @JsonIgnore
    private String password;

    @Enumerated(EnumType.STRING)
    private Status status;

    private String delFlag;

    private String loginIp;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private java.sql.Timestamp loginDate;

    private String remark;

    private Long recycleCompanyId;

    private Long medicalInstitutionId;

    private Long ethnicity;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "sys_user_role",
            joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id")})
    private Set<SysRole> sysRoles;

}

测试

这样,我们在增删改查方法调用时,就会执行我们对应的callback注解的方法
比如我们插入用户

@GetMapping("/save")
    public Long save(){
        SysUser sysUser = new SysUser();
        sysUser.setNickName("测试123321");
        sysUser.setUserName("测试123321");
        sysUser.setSex("0");
        sysUserRepository.save(sysUser);
        return sysUser.getUserId();
    }

保存后,会自动调用postPersist方法

1

评论 (0)

取消