hibernate-符合Java习惯的关系数据库持久化---帮助文档.chm
7.2.1 多队一(many to one)
单向many-to-one关联是最常见的单向关联关系。
表有两张
<1>Person(人)
create table Person
(
personId bigint not null primary key,
addressId bigint not null
)
<2>Address(地址)
create table Address
(
addressId bigint not null primary key
)
hibernate创建的关联关系如下:
类 :Person
<class name = "Person">
<id name = "id" column = "personId">
<generator class = "native"/>
</id>
<many-to-one name = "address" column = "addressId" not-null= "true"/>
</class>
类 :Address
<class name = "Address">
<id name = "id" column = "addressId">
<generator class = "native"/>
</id>
<class >
创建了单向的多对一,这意味着只能从一端访问另一端,而不能双向访问
以上是 人 和 地址 的关系,那是什莫样的关系呢,想想 根据以上的创建是创建了人和地址的多对一的关联
这意味着只能在多的一方访问另一方,而不能在odd的一方访问另一方了。
/*************************************************************************************************/
7.2.2 一对一 (one to one)
<1> 基于外键关联的单向一对一关联和单向多对一关联几乎一样的。
唯一的不同就是单向一对一关联中的外键字段具有唯一性约束。
表有两张
<1>Person(人)
create table Person
(
personId bigint not null primary key,
addressId bigint not null unique---唯一约束
)
<2>Address(地址)
create table Address
(
addressId bigint not null primary key
)
hibernate创建的关联关系如下:
<class name = "Person">
<id name = "id" column = "personId">
<generator class = "native"/>
</id>
<many-to-one name = "address" column = "addressId" unique = "true"
not-null = "true">
</class>
<2>基于主键关联的单向一对一关联通常用一个特定的Id生成器。(请注意,在这个例子中我们调换了关系方向。)
<1>Person(人)
create table Person
(
personId bigint not null primary key,
)
<2>Address(地址)
create table Address
(
addressId bigint not null primary key
)
hibernate创建的关联关系如下:
<class name = "Person">
<id name = "id" column = "personId">
<generator class = "native"/>
</id>
</class>
<class name = "Address">
<id name = "id" column = "personId">
<generator class = "foreign">---foreign=外交的...
<param name = "property">
person
</param>
</generator>
</id>
<one-to-one name = "person" constrained = "true"/>---constrained=强迫的
</class>
/*************************************************************************************************/
7.2.3 一对多 (one to many)
基于外键关联的单向一对多关联是一种很好见的情况,并不推荐使用。
<1>Person(人)
create table Person
(
personId bigint not null primary key,
)
<2>Address(地址)
create table Address
(
addressId bigint not null primary key
)
hibernate创建的关联关系如下:
<class name = "Person">
<id name = "id" column = "personId">
<generator class = "native">
</id>
<set name = "addresses">
<key column = "personId" not-null = "true"/>
<one-to-many class = "Address">
</set>
</class>
<class name = "Address">
<id name = "id" column = "addressId">
<generator class = "native"/>
</id>
</class>
我们认为对于这种关联关系最好使用连接表。