在Hibernate中的单向关联(Unidirectional associations)笔记

Hibernate的单向的笔记

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>
我们认为对于这种关联关系最好使用连接表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值