hibernate详解(七)---映射继承关系
程序员文章站
2024-03-04 08:18:59
...
Hibernate支持三种继承映射策略
一.采用 subclass 元素的继承映射
备注:school就是下面的sname
1.建立Person类
package com.eduask.chp.joinsubclass;
public class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.子类Student类
public class Student extends Person{
private String sname;//学校名称
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
<hibernate-mapping package="com.eduask.chp.subclass">
<class name="Person" table="PERSONS" discriminator-value="person1">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<!-- 辨别者列 -->
<discriminator type="string" column="type"></discriminator>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="age" type="int">
<column name="AGE" />
</property>
<!-- 映射子类Student,使用subclass -->
<subclass name="Student" discriminator-value="student1">
<property name="sname" type="string" column="SNAME"></property>
</subclass>
</class>
</hibernate-mapping>
二.采用 joined-subclass 元素的继承映射
修改Person.hbm.xml文件
<hibernate-mapping package="com.eduask.chp.subclass">
<class name="Person" table="PERSONS">
<id name="id" type="int">
<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="sname" type="string" column="SNAME"></property>
</joined-subclass>
</class>
</hibernate-mapping>
三.采用 union-subclass 元素的继承映射
Person.hbm.xml
<hibernate-mapping package="com.eduask.chp.union.subclass">
<class name="Person" table="PERSONS">
<id name="id" type="int">
<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="sname" type="string" column="SNAME"></property>
</union-subclass>
</class>
</hibernate-mapping>
三者的区别:
下一篇: 构造函数借用构造函数继承