三种方法实现表的继承。
1.student和teacher放在一个表中。
2.每个类分别一张表。
3.共用属性一个表,每个子类一张表。
一、第一种实现方式。
student的属性,teacher的属性放在一个表中,用一个字段“fenlei”来区分是学生和老师。
person类
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="discriminator", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue("person")
public class Person {
private int id;
private String name;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.student类
@Entity
@DiscriminatorValue("student")
public class Student extends Person {
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
3、teacher类
@Entity
@DiscriminatorValue("teacher")
public class Teacher extends Person {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
这种方法的缺点是,student和teacher都各有50多个属性,这样表格就很乱。
二、第二种实现方式,每个类一张表
父类person,子类student,teacher都各一个类。父类、子类的ID是不能重复的。
1、person类
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@TableGenerator(
name="t_gen",
table="t_gen_table",
pkColumnName="t_pk",
valueColumnName="t_value",
pkColumnValue="person_pk",
initialValue=1,
allocationSize=1
)
public class Person {
private int id;
private String name;
@Id
@GeneratedValue(generator="t_gen", strategy=GenerationType.TABLE)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2、student类
@Entity
public class Student extends Person {
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
3.teacher类
@Entity
public class Teacher extends Person {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
第二种方法的缺点,ID不能重复,如果要找一个id对应的人,就要遍历所有父表,子表,或者孙表。
第三种方法,在person中存放student和teacher的公共属性,如id和name;在student和teacher类中各存放自己的特性属性。
1.person父类
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {
private int id;
private String name;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.student类
@Entity
public class Student extends Person {
private int score;
public int getScore() {
return score;
} //Person p = Person(load(1));
public void setScore(int score) {
this.score = score;
}
}
3.teacher类
@Entity
public class Teacher extends Person {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}