Association mappings are the often most difficult thing to get right. In this section we'll go through the canonical cases one by one, starting with unidirectional mappings, and then considering the bidirectional cases. We'll use Personand Addressin all the examples.
We'll classify associations by whether or not they map to an intervening join table, and by multiplicity.
Nullable foreign keys are not considered good practice in traditional data modelling, so all our examples use not null foreign keys. This is not a requirement of Hibernate, and the mappings will all work if you drop the nullability constraints.
2. Unidirectional associations
2.1. many to one
A unidirectional many-to-one association is the most common kind of unidirectional association.
xml代码
<classname = "Person">
<idname = "id"column = "personId">
<generatorclass = "native"/>
id>
<many-to-onename = "address"
column = "addressId"
not-null = "true"/>
class>
<classname = "Address">
<idname = "id"column = "addressId">
<generatorclass = "native"/>
id>
class>
sql 代码
createtable Person ( personId bigintnotnullprimarykey , addressId bigintnotnull )
A unidirectional one-to-one association on a primary key usually uses a special id generator. (Notice that we've reversed the direction of the association in this example.)
xml 代码
<classname = "Person">
<idname = "id"column = "personId">
<generatorclass = "native"/>
id>
class>
<classname = "Address">
<idname = "id"column = "personId">
<generatorclass = "foreign">
<paramname = "property"> person param>
generator>
id>
<one-to-onename = "person"constrained = "true"/>
class>
sql 代码
createtable Person ( personId bigintnotnullprimarykey )
We think it's better to use a join table for this kind of association.
<o:p> </o:p>
3. Unidirectional associations with join tables
3.1. one to many
A unidirectional one-to-many association on a join table is much preferred. Notice that by specifying unique="true", we have changed the multiplicity from many-to-many to one-to-many.
xml 代码
<classname = "Person">
<idname = "id"column = "personId">
<generatorclass = "native"/>
id>
<setname = "addresses"table = "PersonAddress">
<keycolumn = "personId"/>
<many-to-manycolumn = "addressId"
unique = "true"
class = "Address"/>
set>
class>
<classname = "Address">
<idname = "id"column = "addressId">
<generatorclass = "native"/>
id>
class>
sql 代码
createtable Person ( personId bigintnotnullprimarykey )