Hibernate 4.2 JPA 2.0 エンティティを仮定すると、フィールドclass EntityA
が含まれます。これまで、私は List に置き換えてはいけないと強く信じていました。代わりに、リスト メソッドを使用する必要があります。@ManyToOne
List<EntityB> bs
bs
new
clear
add
remove
今日、リストを新しいものに置き換えると問題が発生することを大学に示したかったのですが、奇妙なことは何も起こらず、機能し、データベースとエンティティが正しく更新されました。今、私は混乱しています:休止状態の 4.x JPA 2 では、永続化されたエンティティのコレクションを置き換えることが許可されていますか?
OneToMany リレーションシップを持つ 2 つのエンティティは、1 つのサイトによって維持されます。
@Entity
public class EntityA {
@Id long id;
@OneToMany public List<EntityB>bs;
}
@Entity
public class EntityB {
@Id long id;
hashCode and equals based on id
}
問題が見つからなかったテスト
@Test
@Transactional
public testReplaceSet {
//given: a persistent entity a that contains a persistent entity b1
EntityA a = this.entityManager.persist(new EntityA());
EntityB b1 = this.entityManager.persist(new EntityB());
a.bs = new ArrayList();
a.bs = b1;
this.entityManager.flush();
//when: assining a NEW List with an new persistent Entity b2
EntityB b2 = this.entityManager.persist(new EntityB());
a.bs = new ArrayList();
a.bs = b2;
long aId = a.id;
this.entityManager.flush();
this.entityManager.clear();
//then: the collection is correct stored
EntityA AReloaded = this.entityManager.find(EntityA.class, aId);
//here I expected the failure, but there was no!
assertEquals(b2, AReloaded.bs.get(0));
}