JPA(Java Persistence API)学习十九(按类表策略)
1.概述
在按类表策略中,为每个子实体类生成一个单独的表。
与连接策略不同,在按类表策略中不会为父实体类生成单独的表。
以下语法表示按类表策略
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
2.按类表策略示例
描述:我们将员工分为活跃员工和退休员工。
因此,子类ActiveEmployees
和RetiredEmployees
继承父类Employee
的e_id
和e_name
字段。
第一步:创建父类Employee
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name = "employee_details")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Employee implements Serializable {
@Table(name = "employee_details")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Employee implements Serializable {
@Id
private int e_id;
private String e_name;
}
private int e_id;
private String e_name;
}
第二步:创建实体类
ActiveEmployee.java
(它是Employee
类的子类)。 import javax.persistence.*;
@Entity
public class ActiveEmployee extends Employee {
public class ActiveEmployee extends Employee {
private int e_salary;
private int e_experience;
private int e_experience;
public ActiveEmployee(int e_id, String e_name, int e_salary, int e_experience) {
super(e_id, e_name);
this.e_salary = e_salary;
this.e_experience = e_experience;
}
}
super(e_id, e_name);
this.e_salary = e_salary;
this.e_experience = e_experience;
}
}
第三步:创建另一个实体类
RetiredEmployee.java
(它是Employee.java
的子类)。 import javax.persistence.*;
@Entity
public class RetiredEmployee extends Employee {
public class RetiredEmployee extends Employee {
private int e_pension;
public RetiredEmployee(int e_id, String e_name, int e_pension) {
super(e_id, e_name);
this.e_pension = e_pension;
}
super(e_id, e_name);
this.e_pension = e_pension;
}
}
第四步:xml配置(省略)
第五步:执行
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Employee_details");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ActiveEmployee ae1 = new ActiveEmployee(101, "李小云", 10000, 5);
ActiveEmployee ae2 = new ActiveEmployee(102, "张峰", 12000, 7);
ActiveEmployee ae2 = new ActiveEmployee(102, "张峰", 12000, 7);
RetiredEmployee re1 = new RetiredEmployee(103, "王四哥", 5000);
RetiredEmployee re2 = new RetiredEmployee(104, "叶问顶", 4000);
RetiredEmployee re2 = new RetiredEmployee(104, "叶问顶", 4000);
em.persist(ae1);
em.persist(ae2);
em.persist(ae2);
em.persist(re1);
em.persist(re2);
em.persist(re2);
em.getTransaction().commit();
em.close();
emf.close();
emf.close();
第六步:结果查询
学习来源:https://www.yiibai.com/jpa/jpa-table-per-class-strategy.html#article-start