JPA 使用@Where 注解实现全局过滤
一、背景介绍
在互联网项目中,通常删除都不是物理删除,而是逻辑删除。
那么在展示数据的时候需要过滤掉已删除的数据。而 @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 子句的条件,所以写的是数据库字段的名称与实际结果。
二、使用方法
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 {
还没有评论,来说两句吧...