hibernate---关系映射

关系映射

n多对一(Employee - Department)
n一对多(Department-Employee)
n一对一(Person - IdCard)
n多对多(teacher - student)
ncascade(Employee – Department) 
 

多对一(Employee - Department)

 Employee映射文件

 <many-to-one name=”depart” column=”depart_id”/> 

 
  
 



 

一对多(Department-Employee)

Department映射文件添加

<set name=”集合对象属性名”>

  <key column=”外键名”/>

  <one-to-many class=”集合放入的类名”/>

</set> 

 

    class Department{
private Integer id;
private String name;
private Set<Employee> emps
}

 

一对一(Person - IdCard)

1)基于主键的one-to-one(IdCard的映射文件)

<id name=”id”>

  <generator class=”foreign”><param name=”property”>person</param></generator>

<id>

<one-to-one name=” person” constrained=”true”/>

[没有constraned true将不会生成外键约束]

Person映射文件: <one-to-one name=“idCard” />

class Person{
private Integer id;
private String name;
private IdCard idCard
}


class IdCard{
private Integer id;
private java.util.Date useful_life;
private Person person
}

 

2)基于外健的one-to-one,可以描述为多对一,加unique=“true”约束,

IdCard的映射文件 中:

<many-to-one name=”person” column=”person_id” unique=”true” not-null=”true”/>

 <!-唯一的多对一,其实就便成了一对一了就会在Idcard表生成外键-->

☞ Person映射文件不变化:

多对多(student - course)

在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使

用中最好转换成一对多的对象模型;Hibernate会为我们创建中间

关联表,转换成两个一对多。

<set name=“xxx" table=“xxx">

  <key column=“xxx"/>

  <many-to-many class=“xxx" column=“xxx"/>

</set> 

在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使

用中最好转换成一对多的对象模型;Hibernate会为我们创建中间

关联表,转换成两个一对多



 



 

猜你喜欢

转载自243277745.iteye.com/blog/1852160