(5)JPA - 映射单项多对一的关联关系

1 准备工作。

客户和订单是,多对1的关系。
但是一个订单只属于一个客户。

添加属性,添加get和set方法。
(5)JPA - 映射单项多对一的关联关系
加上注解,和主键。 id 的 主键方式是默认的, 自增。
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系

2

映射单向 n-1 的关联关系
使用 @ManyToOne 来映射多对一的关联关系
使用 @JoinColumn 来映射外键.

(5)JPA - 映射单项多对一的关联关系
添加持久化类。
(5)JPA - 映射单项多对一的关联关系
运行, 先让JPS生成数据表,我们来查看结构

(5)JPA - 映射单项多对一的关联关系(5)JPA - 映射单项多对一的关联关系

运行如下代码:
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系

如果我们先保存order再保存customer能不能成功?
(5)JPA - 映射单项多对一的关联关系
运行结果显示:
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
发现运行的时候是两个update
(5)JPA - 映射单项多对一的关联关系
我只有再保存了customer之后,才直到外键是谁
customer才有id嘛。
JPA为了维护这个关系,额外的发了两个update

保存多对一时, 建议先保存 1 的一端, 后保存 n 的一端, 这样不会多出额外的 UPDATE 语句.

3 弄成lazy 加载。

(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
看一下sql语句。
两条select语句。
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
先打印出的order,后发的查询customer语句。

(5)JPA - 映射单项多对一的关联关系
发送一个select,一个delete
(5)JPA - 映射单项多对一的关联关系
(5)JPA - 映射单项多对一的关联关系
此时我们删除外键customer 7
(5)JPA - 映射单项多对一的关联关系
但是order里面有外键关联。。
(5)JPA - 映射单项多对一的关联关系
发现运行此代码报错
(5)JPA - 映射单项多对一的关联关系
不能直接删除 1 的一端, 因为有外键约束.