传智播客hibernate视频教程-读书笔记2

来源:互联网 发布:c语言程序的基本单位是 编辑:程序博客网 时间:2024/05/07 06:39

14~20讲

 

7、多对一(Employee-Department)
   Employee(id,name,depart<Department>)
   Department(id,name)
   Employee.hbm.xml中定义:
      <many-to-one name="depart" column="depart_id">   column值表示Employee的外键,默认对应Department的主键
   save时顺序无所谓,但是建议先save(depart),后在save(employee)

 

8、一对多(Department-Employee)
   Employee(id,name,depart<Department>)
   Department(id,name,emps)   -->private Set<Employee> emps
   Department.hbm.xml中定义:
      <set name="emps">
         <key column="depart_id"/>   --->Employee的外键
  <one-to-many class="Employee"/>
      </set>

 

9、一对一(Person-IDCard)
   Person(id,name,idCard)
   IDCard(id,userfulLife,person)
  
   1)基于主键的一对一(IDCard中的id既是主键也是外键)
   Person.hbm.xml中定义:
      <class name="Person">
 <id name="id">
   <generator class="native"/>
 </id>
  
 <property name="name"/>
 
 <one-to-one name="idCard"/>
      </class>

    IdCard.hbm.xml中定义:
       <class name="IdCard" table="id_card">
    <id name="id">
  <generator class="foreign">
      <param name="property">person</param>
  </generator>
     </id>
  
    <property name="userfulLife"/>
  
    <one-to-one name="person" constrained=true/>
       </class>

 

    2)基于外键的一对一(可以描述为多对一,加上unique="true"约束)
    Person.hbm.xml中定义:
       <class name="Person">
   <id name="id">
      <generator class="native"/>
   </id>
  
   <property name="name"/>
  
   <one-to-one name="idCard" property-ref="person"/>
       </class>

    IdCard.hbm.xml中定义:
        <class name="IdCard" table="id_card">
    <id name="id">
       <generator class="native"/>
    </id>
  
    <property name="userfulLife"/>

    <many-to-one name="person" column="person_id" unique="true" />
 </class>