1

我有一个类的层次结构,如下所示:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@Table(name="Person")
public class Person implements Serializable{

    @Id
    @Column(name = "PersonID", unique = true, nullable = false)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

}

@Entity
@Table(name="Student")
@PrimaryKeyJoinColumn(name="PersonID")
public class Student extends Person{

}

@Entity
@Table(name="Bachelor")
@PrimaryKeyJoinColumn(name="PersonID")
public class Bachelor extends Student{

    @OneToMany(mappedBy = "bachelor", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<BachelorExam> exams;

}

@Entity
@Table(name="Exam")
public class Exam implements Serializable {

    @Id
    @Column(name = "ExamID", unique = true, nullable = false)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
}

@Entity
@Table(name="BachelorExam")
public class BachelorExam implements Serializable {

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "PersonID_FK", referencedColumnName = "PersonID")
    private Bachelor bachelor;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "ExamID_FK", referencedColumnName = "ExamID")
    private Exam exam;
}

我想通过 ID 使用通用方法从适当的表中获取用户(普通学生或学士),如下所示:

<T extends Person> T getStudentById(Long studentId);

这种方法可以是

public <T extends Person> T getUserById(Long personId) {

    List<Class<?>> studentTypes = new LinkedList<>();

    studentTypes.add(Student.class);
    studentTypes.add(Bachelor.class);

    for (Class aClass : studenTypes) {
        List<T> results = getDatabaseProvider().getDataFromDatabase(String.format("select u %s as u " +
        "where u.userId = '%d'", aClass.getName(), userId));

        return results.get(0);
        }
}

问题是当我在数据库中保存一个单身汉对象时,hibernate 也会将单身汉的 id 保存到“学生”表中,所以当我从数据库中获取通过继承类的整个列表的数据时,查询会从表学士表中返回记录,并从表学生中记录,因为两者都包含必需的学生证。

我尝试使用 InheritanceType Table_Per_class 但在这种情况下,hibernate 不会为表 BachelorExam 中的学士学位创建外键。

我怎样才能通过 id 只接收来自表单身汉的记录?

谢谢!

4

0 回答 0