@OneToMany、@ManyToOne以及@ManyToMany讲解--写的不错转了

来源:互联网 发布:php new 对象 编辑:程序博客网 时间:2024/04/30 04:50

一、一对多(@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)
)
注意此时外键定义在多的一方,也就是address表中。

此时,表customer映射为实体CustomerEO,代码如下:

@Entity
@Table(name=”customer”)
public class CustomerEO implements java.io.Serializable {
@OneToMany(cascade={ CascadeType.ALL })
@JoinColumn(name=”customer_id”)
private Collection addresses = new ArrayList();

}
注释@OneToMany的定义代码如下:
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OneToMany {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default LAZY;
String mappedBy() default “”;
}
使用时要注意一下几点问题:
a、targetEntity属性表示默认关联的实体类型。如果集合类中指定了具体类型了,不需要使用targetEntity.否则要指定targetEntity=AddressEO.class。
b、mappedBy属性用于标记当实体之间是双向时使用。

(2) 映射策略—-表关联

详情:点击打开链接

0 0
原创粉丝点击