继承映射在 Annotation 中使用 @Inheritance 注解,并且需要使用 strategy 属性指定继承策略,继承策略有 SINGLE_TABLE、TABLE_PER_CLASS 和 JOINED 三种。
一、SINGLE_TABLE
SINGLE_TABLE 是将父类和其所有的子类集合在一块,存在一张表中,并创建一个新的字段来判断对象的类型。
Person.java:
<div></div>package com.getop.sales.model; import javax.persistence.*; /** * * @ClassName: Person * @Description: 人类 * @author LiYun * @date 2014-8-19 下午6:01:55 * */ @Entity @Table(name = "SALES_PERSON") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.STRING) @DiscriminatorValue("person") public class Person { private Integer id; private String name; @Id @Column(name = "id") @SequenceGenerator(name = "SALES_PERSON_ID", sequenceName = "SALES_PERSON_ID", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SALES_PERSON_ID") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
@Inheritance 的 strategy 属性是指定继承关系的生成策略,@DiscriminatorColumn 注解作用是指定生成的新的判断对象类型的字段的名称和类型,@DiscriminatorValue 注解是确定此类(Person)的标示,即 DiscriminatorColumn 的值。
Student.java:
<div></div>package com.getop.sales.model; import javax.persistence.*; @Entity @DiscriminatorValue("student") public class Student extends Person { private Integer score; public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } }
Teacher.java:
<div>package com.getop.sales.model; import javax.persistence.*; @Entity @DiscriminatorValue("teacher") public class Teacher extends Person { private String title; public String getTitle() { return title; } public void setTitle(String t