2017-01-09 7 views
1

私は以下の(1:n)関係を持っています:SchoolClass - > Students。 SchoolClassは複数の生徒を持つことができ、Studentは1つだけSchoolClassに割り当てることができます。休止状態(SchoolClassクラス)で、私は次のようしている:今Hibernateを使用した@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例外をスローします)1台を変更する2つのコレクションを持っているので、これは、良い方法ではありません:私は、次の試してみました。

誰でもこの方法を知っていますか?または、方法はありますか@hibernate.bag whereにパラメータを挿入するには、状況に応じてwhere節を変更しますか?

ありがとうございます。

EDIT:

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

(これはちょうど簡単な例だったので、私は愚かクラスを使用、 そのために残念)。そして私はベクトルを使用しなければなりません。この部分のコードは変更できません。 – Tom11

+0

私は参照してください。それでも、ブール値フラグを使うことができます。 –

関連する問題