次の多対多マッピングがあります。
public class Student implements
{
@Id
@GeneratedValue
private Integer xID;
@ManyToMany
@JoinTable(name = "x_y",
joinColumns = { @JoinColumn(name = "xID")},
inverseJoinColumns={@JoinColumn(name="yID")})
private Set<Cat> cats;
}
public class Cat implements
{
@Id
@GeneratedValue
private Integer yID;
@ManyToMany
@JoinTable(name = "x_y",
joinColumns = { @JoinColumn(name = "yID")},
inverseJoinColumns={@JoinColumn(name="xID")})
private Set<Student> students;
}
オブジェクト名とプロパティ名は無視してください。これらは架空のものであり、無関係です。これはコンパイルされ、正常に動作します。私もこれを行うことができます:
Entitymanager em = emf.createEntityManager();
em.getTransaction().begin();
Student s = new Student();
Student s2 = new Student();
Cat c = new Cat();
em.persist(s);
em.persist(s2);
em.persist(c);
s.getCats().add(c);
c.getStudents().add(s2);
em.getTransaction().commit();
私の問題は、データベースからオブジェクトを取り戻すときに発生します。
em.getTransaction().begin();
Student s = em.find(Student.class, 2);
Cat c = em.find(Cat.class, 3);
if( c != null )
System.out.println(c.getYID() + ": " + c.getStudents());
if( s != null )
System.out.println(s.getXID() + ": " + s.getCats());
em.getTransaction().commit();
印刷物は次のとおりです。
3: {IndirectSet: インスタンス化されていません}
2: {IndirectSet: インスタンス化されていません}
これは正常な動作である可能性があります。テーブルからオブジェクトを取得すると、他のオブジェクトに関連するセットを設定する必要があるように思えます。つまり、ジャンクション テーブルは次のようになります。
X | よ
2 | 3
1 | 3
em.find(Cat.class,3) は getStudents() に対して {1,2} のセットを持つ Cat オブジェクトを返す必要があり、em.find(Student.class,2) は {3 のセットを持つ Student オブジェクトを返す必要がありますgetCats() の場合。
これを可能にする方法はありますか?
ありがとう、BJ