Fork me on GitHub

JPA 使用@Where 注解实现全局过滤

JPA 使用@Where 注解实现全局过滤


 

1、背景

在互联网项目中,通常删除都不是物理删除,而是逻辑删除

那么在展示数据的时候需要过滤掉已删除的数据。而@Where 注解可以说就是为此而设计的。

/**
 * Where clause to add to the element Entity or target entity of a collection.  The clause is written in SQL.
 * A common use case here is for soft-deletes.
 *
 * @author Emmanuel Bernard
 */
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface Where {
    /**
     * The where-clause predicate.
     */
    String clause();
}

大致意思为通常添加在集合实体类上作为sql 的where条件使用,常见的使用方式是软删除

因为是where 子句的条件,所以写的是数据库字段的名称与实际结果。

 

2、使用

1)在集合上添加

@Where(clause = "status != \"delete\"")
private List<OptMenu> children= new ArrayList<>(0);

 

2)在实体类上添加

@Entity
@Data
@Table(name = "opt_menu")
@Where(clause = "status not in('delete', 'hidden')")
public class OptMenu {

 

posted @ 2020-09-23 17:50  龙凌云端  阅读(2024)  评论(0编辑  收藏  举报