首页 > 代码库 > (十二)Hibernate中的多表操作(1):单向多对一

(十二)Hibernate中的多表操作(1):单向多对一

  • 由“多”方可知“一”方的信息,比如多个员工使用同一栋公寓,员工可以知道公寓的信息,而公寓无法知道员工的信息。

 

案例一:

  • pojo类
 public class Department {    //公寓类,“一”方
  
        private int id;  
        private String name;  
          //setter和getter方法....  
    }  
public class Employee {   //员工类,“多”方 ,既然是多对一,多方知道一放的信息,那么在多方中必须有一方的对象,
  
    private int id;  
    private String name;  
    private Department department;  
    //setter和getter方法  
}  

 

  • 实体映射文件

Department.hbm.xml如下:

    <?xml version="1.0"?>  
        <!DOCTYPE hibernate-mapping PUBLIC   
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
        <hibernate-mapping package="com.reiyen.hibernate.domain">  
            <class name="Department" >  
                <id name="id" >  
                    <generator class="native" />  
                </id>  
                <property name="name" />  
            </class>  
        </hibernate-mapping>  

Employee.hbm.xml如下:

    <?xml version="1.0"?>  
        <!DOCTYPE hibernate-mapping PUBLIC   
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
        <hibernate-mapping package="com.reiyen.hibernate.domain">  
            <class name="Employee">  
                <id name="id">  
                    <generator class="native" />  
                </id>  
                <property name="name" />  
                <!-- name="department" name的值必须与Employee中的属性名一致. -->  
                <many-to-one name="department" column="depart_id" class="Department" />  
            </class>  
        </hibernate-mapping>  
  • <many-to-one >元素建立了department属性和employee表的外键depart_id之间的映射.

 

  • <many-to-one name=”department” column=”depart_id” />这种缺省情况,
  • hibernate会默认去department对象中查找主键值,因为hibernate默认的是外键对应另一个表中的主键的,
  • 如果想对应department中的其它属性,如”name”,则可以使用<many-to-one name=”department” column=”depart_id” property-ref=”name”/>也可以使用<many-to-one name=”department” />,这与 <many-to-one name=”depart” column=”depart_id” />的唯一区别就是它的column名也为department了,而不是depart_id.

 

  • name: 设定待映射的持久化类的属性名,此外为employee类的department属性.

    column: 设定和持久化类的属性对应的表的外键,此外为employee表的外键depart_id.

    class(可选):设定持久化类的属性的类型,此处设定department的类型是Department类.

    not-null(可选):如果为true,表示department属性不能为null,该属性的默认值为false.当为true时,生成的employee表中depart_id外键会设置not-null约束,所以当Hibernate保存Employee对象时,会先检查它的department属性是否为null,如果为null,则会抛出异常.

 

(十二)Hibernate中的多表操作(1):单向多对一