全部博文(56)
分类: Java
2014-10-10 23:15:21
DROP TABLE IF EXISTS `t_company`; CREATE TABLE `t_company` ( `companyId` int(10) unsigned NOT NULL AUTO_INCREMENT, `companyName` varchar(30) NOT NULL, PRIMARY KEY (`companyId`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=gb2312; INSERT INTO `t_company` VALUES ('1', 'Sun'); INSERT INTO `t_company` VALUES ('2', 'Apache');
DROP TABLE IF EXISTS `t_employee`; CREATE TABLE `t_employee` ( `employeeId` int(10) unsigned NOT NULL AUTO_INCREMENT, `employeeName` varchar(15) NOT NULL, `cid` int(10) unsigned NOT NULL, PRIMARY KEY (`employeeId`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=gb2312; INSERT INTO `t_employee` VALUES ('1', 'Tom', '1'); INSERT INTO `t_employee` VALUES ('2', 'Summ', '1'); INSERT INTO `t_employee` VALUES ('3', 'Cat', '2'); INSERT INTO `t_employee` VALUES ('4', 'Vinylon', '1'); INSERT INTO `t_employee` VALUES ('5', 'Dog', '2');
Employee.java
Company.java
package com.fancy.po; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * ----------------------------------------- * @文件: Employee.java * @作者: fancy * @邮箱: fancyzero@yeah.net * @时间: 2012-6-10 * @描述: 实体类 * ----------------------------------------- */ /** * 下面只说@ManyToOne,如需了解其他注解, * 可以参考上一篇:http://www.cnblogs.com/fancyzero/archive/2012/06/10/hibernate-one-to-one-annotation.html */ @Entity @Table(name = "t_employee") public class Employee { private Integer employeeId; private String employeeName; private Company company; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Integer getEmployeeId() { return employeeId; } /** * @ManyToOne:多对一,cascade:级联,请参考上一篇 * fetch = FetchType.LAZY,延迟加载策略,如果不想延迟加载可以用FetchType.EAGER */ @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH},fetch = FetchType.LAZY) @JoinColumn(name = "cid") public Company getCompany() { return company; } public String getEmployeeName() { return employeeName; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public void setCompany(Company company) { this.company = company; } }
一、一对多(@OneToMany)
1、单向一对多模型
假设通过一个客户实体可以获得多个地址信息。
对于一对多的实体关系而言,表结构有两种设计策略,分别是外键关联和表关联。
(1) 映射策略---外键关联
在数据库中表customer和表结构address定义,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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,代码如下:
1
2
3
4
5
6
7
8
|
@Entity
@Table(name="customer")
public class CustomerEO implements java.io.Serializable {
@OneToMany(cascade={ CascadeType.ALL })
@JoinColumn(name="customer_id")
private Collection
...
}
|
1
2
3
4
5
6
7
|
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OneToMany {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default LAZY;
String mappedBy() default "";
}
|
1
2
3
4
5
|
--客户地址关系表
create table ref_customer_address (
customer_id int(20) not null,
address_id int(20) not null unique
)
|
1
2
3
4
5
6
7
8
9
10
11
|
@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
...
}
|
1
2
3
4
5
6
7
8
9
|
@Target({METHOD,FIELD})
public @interface JoinTable {
String name() default "";
String catalog() default "";
String schema() default "";
JoinColumn[] joinColumns() default {};
JoinColumn[] inverseJoinColumns() default {};
UniqueConstraint[] uniqueConstraints default {};
}
|
其中:
a、该标记和@Table相似,用于标注用于关联的表。
b、name属性为连接两张表的表名。默认的表名为:“表名1”+“-”+“表名2”,上面例子默认的表名为customer_address。
c、joinColumns属性表示,在保存关系中的表中,所保存关联的外键字段。
d、inverseJoinColumns属性与joinColumns属性类似,不过它保存的是保存关系的另一个外键字段。
(3) 默认关联
在数据库底层为两张表添加约束,如下:
1
2
3
4
5
6
7
|
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);
|
二、多对一@ManyToOne
1、单向多对一模型。
(1) 外键关联
配置AddressEO实体如下:
1
2
3
4
5
6
7
8
9
10
|
@Entity
@Table(name="address")
public class AddressEO implements java.io.Serializable {
@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name="customer_id")
private CustomerEO customer;
// ...
}
|
@ManyToOne定义如下:
1
2
3
4
5
6
7
|
@Target({METHOD,FIELD}) @Retention(RUNTIME)
public @interface ManyToOne {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fatch() default EAGER;
boolean optional() default true;
}
|
(2) 默认关联
数据库脚本定义的相关字段的约束,创建外键后,直接使用@ManyToOne
三、高级一对多和多对一映射
即双向关联模型,确定了双向关联后,多的一方AddressEO不变使用@ManyToOne,而CustomerEO实体修改为:
1
2
3
4
5
6
7
8
9
|
@Entity
@Table(name="customer")
public class CustomerEO {
@OneToMany(mappedBy="customer")
private Collection
// ...
}
|