spring-data-jpa软删除方案

maven

        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.postgresql
            postgresql
            runtime
        

配置软删除

@Entity
@Table(name="demo")
@SQLDelete(sql = "update demo set deleted = 1 where id = ?")
@Where(clause = "deleted = 0")
public class Demo{

    @javax.persistence.Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name="deleted")
    private Integer deleted = 0;

    private String userName;

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer deleted) {
        this.deleted = deleted;
    }
}

测试删除及查询

    @Test
    public void testDelete(){
        demoDao.delete(10L);
    }

    @Test
    public void testQuery(){
        List demos = demoDao.findAll();
        System.out.println(demos);
    }

带版本

如果entity带了version,则需要改SQLDELETE为

@SQLDelete(sql = "update demo set deleted = 1 where id = ? and version = ? ")

支持audit

如果有支持audit的话,需要去掉这个SQLDELETE的sql,自己手工update,这样可以确保lastModifiedBy是正确的。

doc

  • How to soft delete a record in Hibernate or JPA / Soft deletion of Entities in Hibernate or JPA

你可能感兴趣的:(spring-data-jpa软删除方案)