Red Hat Training
A Red Hat training course is available for Red Hat JBoss Web Server
8.4. Bidirectional associations
8.4.1. one-to-many / many-to-one
A bidirectional many-to-one association is the most common kind of association. The following example illustrates the standard parent/child relationship.
<class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <set name="people" inverse="true"> <key column="addressId"/> <one-to-many class="Person"/> </set> </class>
create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key )
If you use a
List
, or other indexed collection, set the key
column of the foreign key to not null
. Hibernate will manage the association from the collections side to maintain the index of each element, making the other side virtually inverse by setting update="false"
and insert="false"
:
<class name="Person"> <id name="id"/> ... <many-to-one name="address" column="addressId" not-null="true" insert="false" update="false"/> </class> <class name="Address"> <id name="id"/> ... <list name="people"> <key column="addressId" not-null="true"/> <list-index column="peopleIdx"/> <one-to-many class="Person"/> </list> </class>
If the underlying foreign key column is
NOT NULL
, it is important that you define not-null="true"
on the <key>
element of the collection mapping. Do not only declare not-null="true"
on a possible nested <column>
element, but on the <key>
element.