2014-11-12 6 views
3

JPA 또는 Hibernate 주석을 사용하여 연결된 객체를 검색하기 위해 실행할 쿼리를 명시 적으로 지정할 수 있습니까? 교사, 학생, 및 교사와 학생 사이의 명시 적 OneToOne 관계, 자습서 :관계에 대한 질의를 지정하는 JPA 또는 Hibernate 또는 Spring 주석?

@Entity 
public class Student { 
    @OneToMany Collection<Tutorial> tutorials; 
} 

@Entity 
public class Tutor { 
    @OneToMany Collection<Tutorial> tutorials; 
} 

@Entity 
public class Tutorial { 
    @OneToOne Tutor tutor; 
    @OneToOne Student student; 
    // other data 
} 

학생이 튜토리얼에서는 교사가 숙제를 할당 할 수 있습니다

는 특히, 나는 다음과 같은 요소를 가지고 그래서, (하지만 교사에 의한 학생에 지정되지 않음) :

@Entity 
public class Homework { 
    @ManyToOne Tutorial tutorial; 
    // other data 
} 

가 지금은 학생의 숙제를 모두 검색 할 :

@Entity 
public class Student { 
    @OneToMany Collection<Tutorial> tutorials; 

    @OneToMany Collection<Homework> homework; 
} 

하지만 숙제에는 학생이 없습니다. 그것은 자습서가 있습니다. 이것은 쉽게 SQL로 표현된다 :

select a.* 
from Homework a 
join Tutorial b on (a.tutorial_id = b.id) 
where b.student_id = ?student.id? 

내가이 사용하는 JPA를 명시 적 또는 최대 절전 모드 또는 봄 주석, 그래서 내가 Student.getHomework를 호출 할 때 직접 학생 클래스에서, 그것은 사용() 수 있습니까? 즉

는, 내가 원하는 것은 :

@Entity 
public class Student { 
    @OneToMany Collection<Tutorial> tutorials; 

    @ExplicitQuery("select Homework where Homework.student = this or something") 
    @OneToMany Collection<Homework> homework; 
} 

답변

3
당신은 명명 된 쿼리에 custom loader

@Entity 
@NamedNativeQuery(name="customHomeworkLoader", query="select a.* from Homework a join Tutorial b on (a.tutorial_id = b.id) where b.student_id = ?", resultClass = Homework.class) 
public class Student { 
    @OneToMany Collection<Tutorial> tutorials; 

    @Loader(namedQuery = "customHomeworkLoader") 
    @OneToMany Collection<Homework> homework; 
} 

위치 적 매개 변수 (?)를 사용하여 최대 절전 모드에서이 작업을 수행 할 수 있어야한다

해야 런타임시 자동으로 기본 키로 대체됩니다. 나는이 코드를 시도하지 않았으므로 작동하지 않을 것이라고 보장 할 수는 없지만 진행 방법에 대한 힌트를 줄 수 있기를 바랍니다.

+0

아직 테스트하지는 않았지만 잘 보입니다. 감사! – tpdi

+0

행운을 빌어 요, 고마워요. :) –

관련 문제