5

私の現在のプロジェクトはHSQLDB2.0とJPA2.0を使用しています。

シナリオは次のとおりです。DBにクエリを実行してのリストを取得しcontactDetailsますperson。UIでシングルを削除contactInfoしましたが、そのデータを保存しません(Cancel保存部分)。

もう一度同じクエリを実行します。結果リストは以前の結果よりも1つ少なくなります。UIでcontactInfoを1つ削除しました。しかし、contactInfoクロスチェックすれば、それはDBでまだ利用可能です。

ただし、クエリの開始前に含めるentityManager.clear()と、毎回正しい結果が得られます。

私はこの振る舞いを理解していません。誰かが私にそれを明確にすることができますか?

4

2 に答える 2

16

もう一度クエリを実行するのではなく、次のことを試してください。

entityManager.refresh(person);

より完全な例:

EntityManagerFactory factory = Persistence.createEntityManagerFactory("...");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();

Person p = (Person) em.find(Person.class, 1);
assertEquals(10, p.getContactDetails().size()); // let's pretend p has 10 contact details
p.getContactDetails().remove(0);
assertEquals(9, p.getContactDetails().size());

Person p2 = (Person) em.find(Person.class, 1);
assertTrue(p == p2); // We're in the same persistence context so p == p2
assertEquals(9, p.getContactDetails().size());

// In order to reload the actual patients from the database, refresh the entity
em.refresh(p);
assertTrue(p == p2);
assertEquals(10, p.getContactDetails().size());
assertEquals(10, p2.getContactDetails().size());

em.getTransaction().commit();
em.close();
factory.close();
于 2011-03-14T12:04:29.417 に答える
2

の動作はclear()、そのjavadocで説明されています。

永続コンテキストをクリアして、すべての管理対象エンティティを切り離します。データベースにフラッシュされていないエンティティに加えられた変更は保持されません。

つまり、の削除はcontactInfo永続化されません。

ContactInfoContactDetailsとの間の関係を削除するため、データベースから削除されませんContactInfoが、それ自体は削除されませんContactInfo。削除する場合は、関係で明示的に行うか、関係でremove()指定する必要がありますorphanRemoval = true

于 2011-03-14T07:06:49.960 に答える