2017-12-18 13 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을 알고 있지만 봄 데이터 JPA 사양에 의해 그것을하고 싶다. region은리스트이고 하나의 값과 일치하려고하기 때문에 다음 코드는 작동하지 않아야합니다. 영역 목록을 가져 와서 단일 객체와 비교하는 방법은 무엇입니까?

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

에서 지역 클래스에

+0

도움을 주셔서 감사합니다.하지만 제 경우에는 작동하지 않습니다. jpa criteria 쿼리를 사용하여 다음을 번역해야합니다. FROM 사용자 u 조인 FETCH u.userProfile.country.regions ur WHERE ur.name –

0

코드 조각을 Equals 방법 (또한 해시 코드를) 재정의 평등에 대한 조건을 정의 할 수 있습니다 일을 당신이해야 하나의 술어 만 필요하다면, List의 사용은 과잉 일 수 있습니다.