Hibernate继承映射策略之每棵类继承树一张表

创建一个User类作为父类,ExamAdmin和StudentInfo类继承该User类,在Hibernate中进行映射配置时,可以使用继承映射。每棵类继承树一张表既是User类及其子类对象相关数据存放在一张表中,使用一个标识区别不同的对象。

User类代码:

package com.exam.entity;
public class User {
private String userEmail;
private String userPasswd;
private String userName;
private String userSex;
private String userPhoto;
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPasswd() {
return userPasswd;
}
public void setUserPasswd(String userPasswd) {
this.userPasswd = userPasswd;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public String getUserPhoto() {
return userPhoto;
}
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
}

ExamAdmin类代码:

package com.exam.entity;
public class ExamAdmin extends User {
private SubjectType subjectType;
private String adminLimits;
public String getAdminLimits() {
return adminLimits;
}
public void setAdminLimits(String adminLimits) {
this.adminLimits = adminLimits;
}
public SubjectType getSubjectType() {
return subjectType;
}
public void setSubjectType(SubjectType subjectType) {
this.subjectType = subjectType;
}
}

StudentInfo类代码:

package com.exam.entity;
import java.util.Date;
public class StudentInfo extends User {
private String studentNo;
private Date studentBirth;
private String studentMajor;
private int studentGrade;
private int studentIntegration;
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public Date getStudentBirth() {
return studentBirth;
}
public void setStudentBirth(Date studentBirth) {
this.studentBirth = studentBirth;
}
public String getStudentMajor() {
return studentMajor;
}
public void setStudentMajor(String studentMajor) {
this.studentMajor = studentMajor;
}
public int getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(int studentGrade) {
this.studentGrade = studentGrade;
}
public int getStudentIntegration() {
return studentIntegration;
}
public void setStudentIntegration(int studentIntegration) {
this.studentIntegration = studentIntegration;
}
}

则可以按照以下配置实现每棵类继承树创建一张表:





















其中,标签用于设置子类的标识,如discriminator-value=”A”,则表示该子类在表中相应的标识为A。Subclass标签用于映射子类。

arthinking wechat
欢迎关注itzhai公众号