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 {