每个具体类一个表的方式是只有具体类对应一张表,包括父类和子类,父类和子类的关系是通过
在子类中保存父类的id来实现的。所以保存一条子类的信息需要同时向父类和子类的表中插入记录。
一个例子如下:
· 类Person.java
package com.jason.inheritance.three;
public abstract class Person {
private Long id;
private String name;
/**
* @hibernate.id
* column="ID"
* generator-class="hilo"
* unsaved-value="null"
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* @hibernate.property
* length = "24"
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
· 子类Professor.java
package com.jason.inheritance.three;
public class Professor extends Person {
private int salary;
/**
* @hibernate.property
*/
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
· 子类Student.java
package com.jason.inheritance.three;
public class Student extends Person {
private String studentNumber;
/**
* @hibernate.property
* length = "24"
*/
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
}
· Professor.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> <class name="com.jason.inheritance.three.Professor" table="Professor" dynamic-update="false" dynamic-insert="false" select-before-update="false" optimistic-lock="version"> <id name="id" column="ID" type="java.lang.Long" unsaved-value="null"> <generator class="hilo"> </generator> </id> <property name="salary" type="int" update="true" insert="true" access="property" column="salary"/> <property name="name" type="java.lang.String" update="true" insert="true" access="property" column="name" length="24"/> </class> </hibernate-mapping>
|
· Student.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> <class name="com.jason.inheritance.three.Student" table="Student" dynamic-update="false" dynamic-insert="false" select-before-update="false" optimistic-lock="version"> <id name="id" column="ID" type="java.lang.Long" unsaved-value="null"> <generator class="hilo"> </generator> </id> <property name="studentNumber" type="java.lang.String" update="true" insert="true" access="property" column="studentNumber" length="24"/> <property name="name" type="java.lang.String" update="true" insert="true" access="property" column="name" length="24"/> </class> </hibernate-mapping>
|
显然对应的表是
professor(id, name, salary)
student(id, name, studentNumber)
插入记录的sql如下:
Hibernate: insert into Student (studentNumber, name, ID) values (?, ?, ?)
● 优点:
· 报表操作实现简单:表中包含了具体子类的所有信息。
● 缺点:
· 类的修改会导致相对应的表及其子类所对应表的更改。
· 当含有多重子类时,会造成在数据库表格中生成重复的字段。
参考:
· HIBERNATE - 符合Java习惯的关系数据库持久化(第8章)