JPA规范:过滤子实体 [英] JPA Specification: filter child entities

查看:106
本文介绍了JPA规范:过滤子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的应用程序实体成功实现了软删除(又名删除标志).但是,我还有一个问题. 我用findAll和count方法编写了一个自定义JPARepository,该方法过滤掉了已删除的JPARepository.我用规范来做到这一点:

I successfully implemented a soft delete (aka delete flag) for the entities of my applications. However, I have one remaining problem. I've written a custom JPARepository with findAll and count methods that filter out the deleted ones. I do this with the specification:

softDeleteSpecification = new Specification<T>() {
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.or(cb.isNull(root.get(DELETED_FIELD_NAME)), cb.equal(root.<T>get(DELETED_FIELD_NAME), false));
        }
    };

例如,如果该实体具有一个也要被软删除的OneToMany子实体列表,则该列表不会被过滤,因为查询不是由其存储库运行的.

If the entity has for example a OneToMany child list of entities that are also soft deleted, this list is not filtered because the query is not run by its repository.

我的问题:我可以修改上面的规范,以便将被软删除的子级过滤掉吗? 一种替代方法是使用反射(通常在查询之后)过滤子项,但效果不佳.

My question: Can I modify the specification above so that children that are soft deleted are filtered out? An alternative would be filtering the childs with reflection (manually after the query), but that wouldn't be performant.

推荐答案

我已经开始工作了.如果每个产品都有一个子实体类别,即类别"是产品"的子实体,则以下代码对我有效

I got this working. In case where each product have one child entity category i.e. Category is child entity to Product, below code worked for me

public static Specification<Product> whereCategoryNameEquals(@NonNull String categoryName)  {
    return (Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb) 
        -> cb.equal(root.get(Product_.CATEGORY).get(Category_.CATEGORY_NAME),categoryName);
}

这篇关于JPA规范:过滤子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆