Hibernate(六)单向多对一映射
一、概念
在领域模型中,类与类之间最普遍的关系就是关联关系。
在 UML 中,关联是有方向的:
以 Customer 和 Order 为例: 一个用户能发出多个订单,而一个订单只能属于一个客户;从 Order 到 Customer 的关联是多对一关联,而从 Customer 到 Order 是一对多关联。
二、单向 n-1
单向 n-1 关联只需从 n 的一端可以访问 1 的一端
域模型:从 Order 到 Customer 的多对一单向关联需要在Order 类中定义一个 Customer 属性,而在 Customer 类中无需定义存放 Order 对象的集合属性。
关系数据模型:ORDERS 表中的 CUSTOMER_ID 参照 CUSTOMER 表的主键。
显然无法直接用 property 映射 customer 属性,Hibernate 使用 元素来映射多对一关联关系。
<many-to-one>元素来映射组成关系
name: 设定待映射的持久化类的属性的名字
column: 设定和持久化类的属性对应的表的外键
class:设定待映射的持久化类的属性的类型
三、案例
异常情况:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near Order...........
原因:使用了数据库的关键字才导致了该异常的产生。
(1)Customer.java

(2)Orders.java,这里不要用Order

(3)Customer.hbm.xml

(4)Orders.hbm.xml

(5)hibernate.cfg.xml

(6)执行一下,生成数据库





(7)插入数据
先插入Customer,再插入Order,3条insert语句;也就是先插入 1 的一端,再插入 n 的一端,只有insert语句

先插入Order,再插入Customer,3条insert语句,2条update语句;也就是先插入 n 的一端,再插入 1 的一端,会多出update语句。

(8)若查询多的一端的的一个对象,则默认情况下,只查询了多的一端的对象,而没有查询关联的 1 的那一端的对象!

(9)在需要使用到关联的对象时,才发送对应的SQL语句

(10)在查询Customer对象时,由多的一端导航到 1 的一端时,若此时session已关闭,则默认情况下会发生LazyInitializationException异常,

(11)执行修改操作

(12)执行删除操作:
在不设定级联关系的情况下,且 1 的一端的对象有 n 的对象在引用,不能直接删除 1 这一端的对象
