2017-02-01 1 views
0

최근에 JEE에서 Spring Boot로 바뀌 었습니다. 지금까지 그것을 사랑하고 있습니다. 하지만 조금 문제가 있습니다.스프링 데이터 동적 @Query는 매개 변수를 기반으로 할 수 있습니까?

봄의 데이터와 자신의 멋진 인터페이스 이제
public Foo getParentWithChildren(long id, boolean isFetchChild, boolean isFetchPets) { 
    StringBuilder sql = new StringBuilder(); 
    sql.append("select DISTINCT(p) from Parent p"); 
    if(isFetchChild) { 
     sql.append(" left join p.child c"); 
    } if(isFetchPets) { 
     sql.append(" left join p.pets pts"); 
    } 

    sql.append(" where p.id=:id"); 

    TypedQuery<Foo> query = em.createQuery(sql.toString(), Foo.class); 
    query.setParameter("id", id); 
    return query.getSingleResult(); 
} 

내가 simlar 뭔가 인터페이스의 @query 주석을 사용하는 대신에 갖는하고 싶으면 : 나는 이런 식으로 뭔가를 조회하는 데 사용 게으른 참조를 가져 오는이 방법을 커스텀 구현을 작성합니다. 그러나 인터페이스 만 사용하여 비슷한 작업을 수행 할 수 있습니까?

아래의 예는 작동하지 분명하지만 난 당신이 내가 할 수 비슷한

@Query("select distinct(p) from Parent p " + 
     (fetchChild ? " left join p.child c" : "") + 
     (fetchPets ? " left join p.pets pts" : "") + 
     " where p.id=:id") 
Foo getParentWithChildren(@Param("id") long id, @Param("fetchChild") boolean isFetchChild, @Param("fetchPets") boolean isFetchPets); 

내가 뭔가를 acchieve하려고 이해 바랍니다?

+1

아니,하지만이 정확한 경우, 당신은 isFetchChild''에 따라 적절한 하나를 인터페이스에서이 메소드를 생성하고 메소드를 호출 할 수 있습니다. –

+0

실제로 실제 상위에는 5 개의 부울 매개 변수 (예 : 5 개의 부울 매개 변수)가 있습니다. 그리고 다른 조합도 있습니다. 때로는 아이 1과 3, 다른 시간 4, 때로는 모두 5 등을 원합니다. 그러면 가능한 모든 시나리오에 대해 메소드를 작성해야합니까? – Johan

답변

1

당신은 스프링 데이터 JPA 다양한 방법으로 지원 JPA 2.1에 도입 된 EntityGraph 기능을 사용자 인터페이스에 여러 방법을 만들어 사용할 수 있습니다이와

http://docs.spring.io/spring-data/jpa/docs/1.11.0.RELEASE/reference/html/#jpa.entity-graph

public interface FooRepository extends JpaRepository<Foo, Long>{ 

    @EntityGraph(attributePaths = { "children" }) 
    @Query("select f from Foo f where f.id = :id") 
    Foo getFooWithChildren(@Param("id") long id); 

    @EntityGraph(attributePaths = { "pets" }) 
    @Query("select f from Foo f where f.id = :id") 
    Foo getFooWithPets(@Param("id") long id); 

    @EntityGraph(attributePaths = { "children", "pets" }) 
    @Query("select f from Foo f where f.id = :id") 
    Foo getFooWithChildrenAndPets(@Param("id") long id); 
} 

한 가지 문제는 당신이 필요 각 메소드에 대해 조회를 반복하십시오. 엔티티 그래프를 질의 메소드의 매개 변수로 전달할 수 있다는 것은 스프링 데이터 JPA 모듈에서 유용한 기능이 누락 된 것 같습니다.

나는 몇 시간 전에 이것에 대한 티켓을 제기하지만, 아직 갱신 :

https://jira.spring.io/browse/DATAJPA-645?filter=-2

이 질문에 Spring Data JPA And NamedEntityGraphs에 대한 답변에서 링크는하지만 그 이하 우리가 정확히이 작업을 수행 할 수 있습니다에 연장을 제안하지 :

이 익스텐션

https://github.com/Cosium/spring-data-jpa-entity-graph

코드가 단순화되고

public interface FooRepository extends JpaEntityGraphRepository<Foo, Long>{ 

} 

과로 전화 :

Foo foo = fooRepository.findOne(1L, 
       new DynamicEntityGraph(Arrays.asList({"children"); 

Foo foo = fooRepository.findOne(1L, 
       new DynamicEntityGraph(Arrays.asList({"children", "pets"}); 
+0

고마워요! 나는 이것을 조사 할 것이다. 질문, 참조 된 엔티티는 기본적으로 내부 조인에 의해 반입됩니까? 그렇다면 왼쪽 조인 또는 다른 유형을 원한다고 지정할 수 있습니까? – Johan

관련 문제