Hibernate已加入的继承:仅通过子表从ID查询记录

时间:2017-03-03 09:29:27

标签: java hibernate joined-subclass

我有下一个类的层次结构:

@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保存到“学生”表中,所以当我从数据库中获取数据时,通过整个继承类列表,查询从表单学士返回记录并记录来自表格Student,因为两者都包含所需的学生证。

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

我如何只能通过身份证收到表格Bachelor的记录?

谢谢!

0 个答案:

没有答案