2017-01-09 46 views
1

다음과 같은 (1 : n) 관계가 있습니다 : SchoolClass -> Students. SchoolClass에는 여러 명의 학생이있을 수 있으며 StudentSchoolClass 하나에만 할당 할 수 있습니다. 최대 절전 모드 (SchoolClass 클래스)에서, 나는 다음과 같은 한 : 이제최대 절전 모드를 사용하는 @OneToMany 백 관계에 대한 다중 참조

private transient List students; 

    /** 
    * @return Returns students. 
    * @hibernate.bag lazy="true" cascade="all" where="(graduated_with_honors=0)" 
    * @hibernate.collection-key column="class_id" 
    * @hibernate.collection-one-to-many class="my.project.namespace.Student" 
    */ 
    public List getStudents() { 
     if (students == null) { 
      students = new Vector(); 
     } 
     return students; 
    } 

, 나는 다른 방법을 만들려면, 즉 우수한 성적으로 졸업 SchoolClass (또한 사람의 모든 학생들을 나열 그래서 graduated_with_honors이 될 수 있습니다 0 또는 1). 나는 다음과 같은 시도 :

private transient List students, allStudents; 

    /** 
    * @return Returns students. 
    * @hibernate.bag lazy="true" cascade="all" where="(graduated_with_honors=0)" 
    * @hibernate.collection-key column="class_id" 
    * @hibernate.collection-one-to-many class="my.project.namespace.Student" 
    */ 
    public List getStudents() { 
     if (students == null) { 
      students = new Vector(); 
     } 
     return students; 
    } 

    /** 
    * @return Returns students. 
    * @hibernate.bag lazy="true" cascade="all" 
    * @hibernate.collection-key column="class_id" 
    * @hibernate.collection-one-to-many class="my.project.namespace.Student" 
    */ 
    public List getAllStudents() { 
     if (allStudents == null) { 
      allStudents = new Vector(); 
     } 
     return allStudents; 
    } 

하지만 지금 우리가 하나 개의 테이블을 수정 두 개의 컬렉션을 가지고 있기 때문에이 사용될 때 (이 hibernate found shared references to a collection 예외를 슬로우), 좋은 방법이 아니다.

아무에게도이를 수행하는 방법을 알고 있습니까? 또는 방법이 있습니까 @hibernate.bag where 절에 매개 변수를 삽입하는 방법은이므로 상황에 따라 where 절을 변경 하시겠습니까?

미리 감사드립니다.

편집 :

private transient List students; 

-이 나는 그대로 유지해야 동일하게 유지해야합니다.

답변

1

당신의 매핑에 잘못 여러 가지가 있습니다

  1. 컬렉션은 항상 null이 있어야합니다

    private List<Student> students = new ArrayList<>(); 
    
  2. 이 왜 대신 ListVector를 사용합니까이? Vector은 동기화되지만 ArrayList은 동기화되지 않습니다. 엔티티를 동시에 사용 하시겠습니까?

  3. class은 java에서 예약되어 있으므로 사용할 수 없으므로 Course으로 이름을 바꾸는 것이 좋습니다.

  4. graduated_with_honors 관계는 Student 클래스에서 부울로 가장 잘 표현할 수 있습니다.

    private boolean graduatedWithHonor; 
    

그렇다면, 당신은 간단하게 조회 할 수있는 모든 명예를 졸업 한 Student(s) : 나는 SchoolClass에 클래스 이름을 변경 한

Course course = ...; 

List<Student> honourableStudents = entityManager.createQuery(
     "select s " + 
     "from Student s " + 
     "where s.graduatedWithHonor = true " + 
     "and s.course = :course", Student.class) 
.setParameter("course", course) 
.getResultList(); 
+0

(이 그냥 간단한 예, 그래서 내가 어리석게 클래스를 사용 , 그 죄송합니다). 그리고 Vector를 사용해야하는데,이 부분은 변경할 수 없습니다. – Tom11

+0

알겠습니다. 그럼에도 불구하고 부울 플래그를 사용할 수 있습니다. –