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 {

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM