我正在开发一个学生管理应用程序,我对如何使用继承将数据库中具有的不同类型的用户与Java类进行映射感到困惑。我有如下表格“ User”,“ Student”和“ Teacher”:
我创建了抽象类User:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "user")
public abstract class User {
@Id
private int id;
private String fname;
private String lname;
private String email;
private String password;
private String address;
private String phone;
private String userType;
private boolean isAdmin;
public User(String fname, String lname, String email, String password, String address, String phone,
String userType, boolean isAdmin) {
//super();
this.fname = fname;
this.lname = lname;
this.email = email;
this.password = password;
this.address = address;
this.phone = phone;
this.userType = userType;
this.isAdmin = isAdmin;
}
儿童班学生:
@Entity
@Table(name = "student")
public class Student extends User {
@Id
@Column(name = "user_id")
private int id;
private int grade;
public Student(int id, String fname, String lname, String email, String password, String address, String phone,
String userType, int grade, boolean isAdmin)
{
super(fname, lname, email, password, address, phone, userType, isAdmin);
this.grade=grade;
this.id = id;
}
“老师”课程的使用方式与“学生”课程相同。
为了使用数据库从学生创建,读取,更新或删除学生,我陷入了如何使用hibernate实际建立关系模型的困境。
到目前为止,我已经在StudentDAO类中尝试了此方法,但是它无法正常工作,我真的不确定我的建模是否正确:
@Transactional
public void listStudent( int id ){
Student myStudent =null;
Configuration con = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class);
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
myStudent = (Student)session.get(Student.class, id);
System.out.println(myStudent);
我对如何使用一对多关系感到困惑,因为我将其视为继承。
如何以最佳方式对此进行建模,以及如何使用hibernate仅在数据库上使用这些基本操作?