继承映射在 Annotation 中使用 @Inheritance 注解,并且需要使用 strategy 属性指定继承策略,继承策略有 SINGLE_TABLE、TABLE_PER_CLASS 和 JOINED 三种。
一、SINGLE_TABLE
SINGLE_TABLE 是将父类和其所有的子类集合在一块,存在一张表中,并创建一个新的字段来判断对象的类型。
Person.java:
1: @Entity
2: @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
3: @DiscriminatorColumn(name="discriminator",discriminatorType=DiscriminatorType.STRING)
4: @DiscriminatorValue("person")
5: public class Person {
6: @Id
7: @GeneratedValue
8: private int id;
9: private String name;
10: //Getters and setters omitted here...
11: }
@Inheritance 的 strategy 属性是指定继承关系的生成策略,@DiscriminatorColumn 注解作用是指定生成的新的判断对象类型的字段的名称和类型,@DiscriminatorValue 注解是确定此类(Person)的标示,即 DiscriminatorColumn 的值。
Student.java:
1: @Entity
2: @DiscriminatorValue("student")
3: public class Student extends Person{
4: private int score;
5: //Getters and setters omitted here...
6: }
Teacher.java:
1: @Entity
2: @DiscriminatorValue("teacher")
3: public class Teacher extends Person{
4: private String title;
5: //Getters and setters omitted here...
6: }
生成的数据库表如下:
存入数据后结构如下:
二、TABLE_PER_CLASS
TABLE_PER_CLASS 是为每一个类创建一个表,这些表是相互独立的。
Person.java:
1: @Entity
2: @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
3: public class Person {
4: @Id
5: private int id;
6: private String name;
7: //Getters and setters omitted here...
8: }
Student.java:
1: @Entity
2: public class Student extends Person{
3: private int score;
4: //Getters and setters omitted here...
5: }
Teacher.java:
1: @Entity
2: public class Teacher extends Person{
3: private String title;
4: //Getters and setters omitted here...
5: }
创建的数据库表如下:
三、JOINED
JOINED 是将父类、子类分别存放在不同的表中,并且建立相应的外键,以确定相互之间的关系。
Person.java:
1: @Entity
2: @Inheritance(strategy=InheritanceType.JOINED)
3: public class Person {
4: @Id
5: @GeneratedValue
6: private int id;
7: private String name;
8: //Getters and setters omitted here...
9: }
子类中只需声明与父类不同的域即可:
Student.java:
1: @Entity
2: public class Student extends Person{
3: private int coat;
4: //Getters and setters omitted here...
5: }
Teacher.java 类似。
生成的数据库表如下:
转:http://blog.csdn.net/mzule/article/details/6194188