1. 程式人生 > 實用技巧 >JPA 使用@Where 註解實現全域性過濾

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 {