Spring数据jpa规范:如何通过子对象属性过滤父对象

时间:2017-12-18 11:04:51

标签: spring hibernate spring-boot spring-data-jpa jpa-criteria

我的实体类正在关注

@Entity
@table
public class User {

    @OneToOne
    private UserProfile userProfile;

    // others
}


@Entity
@Table
public class UserProfile {

    @OneToOne
    private Country country;
}

@Entity
@Table
public class Country {
    @OneToMany
    private List<Region> regions;
}

现在我希望获得特定区域的所有用户。我知道sql但我想通过spring data jpa规范来做。以下代码不起作用,因为区域是一个列表,我试图匹配单个值。如何获取区域列表并与单个对象进行比较?

 public static Specification<User> userFilterByRegion(String region){


        return new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                return criteriaBuilder.equal(root.get("userProfile").get("country").get("regions").get("name"), regionalEntity);
            }
        };
    }

编辑:感谢您的帮助。实际上我正在寻找以下JPQL的等效标准查询

SELECT u FROM User u JOIN FETCH u.userProfile.country.regions ur WHERE ur.name=:<region_name>

2 个答案:

答案 0 :(得分:3)

试试这个。这应该工作

criteriaBuilder.isMember(regionalEntity, root.get("userProfile").get("country").get("regions"))

您可以通过覆盖Region类中的Equals方法(也是Hashcode)来定义相等的条件

答案 1 :(得分:0)

我的代码片段

// string constants make maintenance easier if they are mentioned in several lines
private static final String CONST_CLIENT = "client";
private static final String CONST_CLIENT_TYPE = "clientType";
private static final String CONST_ID = "id";
private static final String CONST_POST_OFFICE = "postOffice";
private static final String CONST_INDEX = "index";
...

@Override
public Predicate toPredicate(Root<Claim> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    // we get list of clients and compare client's type
    predicates.add(cb.equal(root
                .<Client>get(CONST_CLIENT)
                .<ClientType>get(CONST_CLIENT_TYPE)
                .<Long>get(CONST_ID), clientTypeId));
    // Set<String> indexes = new HashSet<>();
    predicates.add(root
                .<PostOffice>get(CONST_POST_OFFICE)
                .<String>get(CONST_INDEX).in(indexes));
    // more predicates added
    return return andTogether(predicates, cb);
}

private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
    return cb.and(predicates.toArray(new Predicate[0]));
}

如果你确定,你只需要一个谓词,那么使用List可能是一种过度杀伤。