このコンテンツは選択した言語では利用できません。

21.2. Bidirectional one-to-many


Suppose we start with a simple <one-to-many> association from Parent to Child.
<set name="children">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>
Copy to Clipboard Toggle word wrap
If we were to execute the following code:
Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();
Copy to Clipboard Toggle word wrap
Hibernate would issue two SQL statements:
  • an INSERT to create the record for c
  • an UPDATE to create the link from p to c
This is not only inefficient, but also violates any NOT NULL constraint on the parent_id column. You can fix the nullability constraint violation by specifying not-null="true" in the collection mapping:
<set name="children">
    <key column="parent_id" not-null="true"/>
    <one-to-many class="Child"/>
</set>
Copy to Clipboard Toggle word wrap
However, this is not the recommended solution.
The underlying cause of this behavior is that the link (the foreign key parent_id) from p to c is not considered part of the state of the Child object and is therefore not created in the INSERT. The solution is to make the link part of the Child mapping.
<many-to-one name="parent" column="parent_id" not-null="true"/>
Copy to Clipboard Toggle word wrap
You also need to add the parent property to the Child class.
Now that the Child entity is managing the state of the link, we tell the collection not to update the link. We use the inverse attribute to do this:
<set name="children" inverse="true">
    <key column="parent_id"/>
    <one-to-many class="Child"/>
</set>
Copy to Clipboard Toggle word wrap
The following code would be used to add a new Child:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();
Copy to Clipboard Toggle word wrap
Only one SQL INSERT would now be issued.
You could also create an addChild() method of Parent.
public void addChild(Child c) {
    c.setParent(this);
    children.add(c);
}
Copy to Clipboard Toggle word wrap
The code to add a Child looks like this:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.save(c);
session.flush();
Copy to Clipboard Toggle word wrap
トップに戻る
Red Hat logoGithubredditYoutubeTwitter

詳細情報

試用、購入および販売

コミュニティー

Red Hat ドキュメントについて

Red Hat をお使いのお客様が、信頼できるコンテンツが含まれている製品やサービスを活用することで、イノベーションを行い、目標を達成できるようにします。 最新の更新を見る.

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

Theme

© 2025 Red Hat