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 {
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步