Hibernate一对一关系映射
实体之间的联系
- 一对一联系
- 一对多联系
- 多对多联系
Hibernate一对一关联关系映射
1、 主键关联映射
(1)通过one-to-one元素配置
①在外键表中指定为外键表,指定user为外键
<id name="id">
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>
<one-to-one name="user" constrained="true"></one-to-one>
②在主表中
指定person的类,设置关联方式,这里所有的都是级联
<one-to-one name="person" class="Person" cascade="all"></one-to-one>
2、唯一外键关联映射
(1)外键必须设定unique约束
(2)通过many-to-one元素配置
person表为主键表,使用property-ref属性,表明从User到Person的一对一关联关系
<one-to-one name="user" property-ref="person"></one-to-one>
user表为外键表只需要在user表中通过设置即可
<many-to-one name="person" column="personid" cascade="all" unique="true"></many-to-one>
使用配置文件配置
使用注解配置
值得注意的是在使用注解配置的过程中根据注解的位置的不同会有两种情况
1、放在属性前面(依据映射方式)
2、放在get,set方法前面(get,set方法)
这两种方式不可以混用,都放在属性前面或都放在方法前面,否则会出现引用异常(空指针错误)
Hibernate组合关系映射
如这个地址类,homeAddress和workAddress都需要借助这样一个类,如果没有这个单独的类,就会又多出许多的字段
配置文件
<hibernate-mapping package="com.hibernate.entity">
<class name="Contact" table="contact">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="phoneNum"></property>
<property name="email"></property>
<!-- class指定类型 -->
<component name="homeAddress" class="Address">
<property name="province" column="province"></property>
<property name="city" column="city"></property>
<property name="district" column="district"></property>
<property name="detail" column="detail"></property>
</component>
</class>
</hibernate-mapping>
需要多出一个属性,component来指定
使用注解配置映射组合关系
在部分类上使用@Embeddable指定
在整体类上,在部分类所对应的属性上使用@Embedded来指定
使用@AttributeOverrides来指定部分类中对应的属性
public class Contact {
@Id
@GeneratedValue(generator = "generator")
@GenericGenerator(name = "generator",strategy = "increment")
private int id;
private String phoneNum;
private String email;
@Embedded
@AttributeOverrides(value = {
@AttributeOverride(name = "provice",column = @Column(name="provice")),
@AttributeOverride(name = "city", column = @Column(name="city")),
@AttributeOverride(name = "district", column = @Column(name="district")),
@AttributeOverride(name = "detail", column = @Column(name="detail"))
})
private Address homeAddress;
}