JPA基础(十四):JPA中的继承映射关系

Employee.java:(基类)

 1 @Entity
2 @Inheritance(strategy=InheritanceType.SINGLE_TABLE)//选择继承策略
3 @DiscriminatorColumn(name="type")//配置鉴别器
4 @DiscriminatorValue("0")//设置鉴别器值
5 public class Employee {
6 @Id
7 @GeneratedValue
8 private Integer id;
9 private String name;
10 public Integer getId() {
11 return id;
12 }
13 public void setId(Integer id) {
14 this.id = id;
15 }
16 public String getName() {
17 return name;
18 }
19 public void setName(String name) {
20 this.name = name;
21 }
22 }

其中@Inheritance(strategy=InheritanceType.SINGLE_TABLE)//选择继承策略 可以选择多种策略,如下图所示:

JPA基础(十四):JPA中的继承映射关系_第1张图片

  • JOINED:继承的子类各自生成一张表
  • SINGLE_TABLE:只生成一张表,用一个字段当鉴别器
  • TABLE_PER_CLASS:每个类都生产一张表,包括基类

 

Skiller.java(继承自Employee.java)

 1 @Entity
2 @DiscriminatorValue("1")
3 public class Skiller extends Employee {
4 private String skill;
5
6 public String getSkill() {
7 return skill;
8 }
9
10 public void setSkill(String skill) {
11 this.skill = skill;
12 }
13 }

Sales.java(继承自Employee.java)

 1 @Entity
2 @DiscriminatorValue("2")
3 public class Sales extends Employee {
4 private String sell;
5 public String getSell() {
6 return sell;
7 }
8 public void setSell(String sell) {
9 this.sell = sell;
10 }
11 }

测试:

 1     @Test
2 public void save(){
3 EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");
4 EntityManager em=factory.createEntityManager();
5 em.getTransaction().begin();
6 Employee p1=new Employee();
7 p1.setName("Jim");
8 Skiller p2=new Skiller();
9 p2.setName("Hanson");
10 p2.setSkill("skill");
11 Sales p3=new Sales();
12 p3.setName("Brian");
13 p3.setSell("sale");
14 em.persist(p1);
15 em.persist(p2);
16 em.persist(p3);
17 em.getTransaction().commit();
18 em.close();
19 factory.close();
20 }

打开数据库:




你可能感兴趣的:(jpa)