hibernate注解@manytoone,@onetomany
一、一对多(@onetomany)
1、单向一对多模型
假设通过一个客户实体可以获得多个地址信息。
对于一对多的实体关系而言,表结构有两种设计策略,分别是外键关联和表关联。
(1) 映射策略---外键关联
在数据库中表customer和表结构address定义,如下:
create table customer ( id int(20) not null auto_increment, name varchar(100), primary key(id) ) create table address ( id int(20) not null auto_increment, province varchar(50), city varchar(50), postcode varchar(50), detail varchar(50), customer_id int(20), primary key (id) )
此时,表customer映射为实体CustomerEO,代码如下:
@Entity @Table(name="customer") public class CustomerEO implements java.io.Serializable { @OneToMany(cascade={ CascadeType.ALL }) @JoinColumn(name="customer_id") private Collection<AddressEO> addresses = new ArrayList<AddressEO>(); ... }
(2) 映射策略---表关联
在上面address表中去掉customer_id字段,在增加一个表ref_customer_address,如下: --客户地址关系表
create table ref_customer_address ( customer_id int(20) not null, address_id int(20) not null unique )
此时表customer映射为CustomerEO实体,代码如下:
@Entity @Table(name = "customer") public class CustomerEO implements java.io.Serializable { ... @OneToMany(cascade = { CascadeType.ALL }) @JoinTable(name="ref_customer_address", joinColumns={ @JoinColumn(name="customer_id",referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="address_id",referencedColumnName="id")}) private Collection<AddressEO> addresses = new ArrayList<AddressEO>(); ... }
(3) 默认关联
在数据库底层为两张表添加约束,如下:
create table customer_address ( customer_id int(20) not null, address_id int(20) not null unique ) alter table customer_address add constraint fk_ref_customer foreign key (customer_id) references customer (id); alter table customer_address add constraint fk_ref_address foreign key (address_id) references address (id);
这样,在CustomerEO中只需要在标注@OneToMany即可!
二、多对一@ManyToOne
1、单向多对一模型。
(1) 外键关联
配置AddressEO实体如下:
@Entity @Table(name="address") public class AddressEO implements java.io.Serializable { @ManyToOne(cascade = { CascadeType.ALL }) @JoinColumn(name="customer_id")//外键字段 private CustomerEO customer; // ... }
三、高级一对多和多对一映射
即双向关联模型,确定了双向关联后,多的一方AddressEO不变使用@ManyToOne,而CustomerEO实体修改为:
@Entity @Table(name="customer") public class CustomerEO { @OneToMany(mappedBy="customer") private Collection<AddressEO> addresses = new ArrayList<AddressEO>(); // ... }
其中,@OneToMany标记中的mappedBy属性的值为AddressEO实体中所引用的CustomerEO实体的属性名。
四、多对多(@ManyToMany)和一对多类似