2017-12-18 212 views
0

我的实体类以下春数据JPA规范:如何通过它的孩子来过滤父对象对象属性

@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 Specification来完成。下面的代码不应该工作,因为地区是一个列表,我试图匹配一个单一的值。如何获取区域列表并与单个对象进行比较?

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> 

回答

1

等效标准查询试试这个。这应该工作

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

你可以从我的代码

// 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])); 
} 

在区域类中重写Equals方法(也凑码)

+0

感谢您的帮助,但它不适用于我的情况。我需要翻译下面的jpa条件查询。 FROM User你好JOIN FETCH u.userProfile.country.regions你在哪里你的名字 –

0

片段定义为平等的条件,如果你是肯定的,那你只需要一个谓词,List的使用可能是一个矫枉过正的问题。