Hibernate关于父类子类的映射

怕忘记,把栗子贴上来

以Person类和Student类为例

public class Person
{
    private Integer id;
    private String name;
    private int age;
        //省略setter、getter代码
}

 

public class Student extends Person
{
    private String school;
   //省略setter、getter代码
}

第一种方式:只有一张表的

直接贴映射文件内容

<hibernate-mapping package="com.zcd.exercise.subclass">
    <class name="Person" table="PERSONS" discriminator-value="PERSON">
    
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        
        <discriminator type="string">
            <column name="TYPE"></column>
        </discriminator>
        
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        
        <property name="age" type="int">
            <column name="AGE" />
        </property>
        
        <subclass name="Student" discriminator-value="STUDENT">
            <property name="school" type="string" column="SCHOOL"></property>
        </subclass>
        
    </class>
</hibernate-mapping>

第二种方式:分两张表存储

<hibernate-mapping package="com.zcd.exercise.unionSubclass">
    <class name="Person" table="PERSONS">
    
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="hilo" />
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        
        <property name="age" type="int">
            <column name="AGE" />
        </property>
        
        <union-subclass name="Student" table="STUDENTS">
            <property name="school" type="string">
                <column name="SCHOOL"></column>
            </property>
        </union-subclass>
         
    </class>
</hibernate-mapping>

 第三种方式:也是分两张表但是会把子类特有的属性单独存放在一张表,也就是相当于把一条记录拆开放在两张表中。

<hibernate-mapping package="com.zcd.exercise.joinedSubclass">
    <class name="Person" table="PERSONS">
    
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        
        <property name="age" type="int">
            <column name="AGE" />
        </property>
        
        <joined-subclass name="Student" table="STUDENTS">
            <key column="STUDENT_ID"></key>
            <property name="school" type="string" column="SCHOOL"></property>
        </joined-subclass>
         
    </class>
</hibernate-mapping>

 

posted @ 2017-09-25 16:11  钓鱼翁  阅读(636)  评论(0编辑  收藏  举报