Spring 数据 jpa 规范 : How to filter a parent object by its children object property

标签 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 数据 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>

最佳答案

尝试这个。这应该工作

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

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

关于Spring 数据 jpa 规范 : How to filter a parent object by its children object property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47867124/

相关文章:

java - Spring 数据JPA : how to return empty result when repository method parameter of Collection type is empty?

java - 如何在 JPA 和 Hibernate 4.3 中使用 SchemaExportTool

java - 如何将表与该表的实体类中 View 的一列连接起来

java - 在非嵌入式 Tomcat 上使用 SSL 运行 SpringBoot

java - Spring JavaConfig 没有捕获 PageNotFound?

java - Angular $http - spring - 抛出异常但http状态为200

spring - Spring 3.1 Junit测试中获取WebApplicationContext

Java Hibernate暂时忽略带有条件的@ManyToOne注释

spring-boot - 我们如何在pcf中为微服务配置API网关、服务发现?

java - Hibernate-Spring boot : spring. jpa.hibernate.ddl-auto=update 更新实体后重新创建表和列