比如说,现在有4个实体:Person,Teacher,Student,和Account,Teacher和Student继承自Person,Account与Person是单向的一对一关系。(这只是为了举例,请不要考虑诸如这样的实体设计是否合理的问题)如下所示:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class Person {
......
}
@Entity
@DiscriminatorValue("teacher")
public class Teacher extends Person {
......
}
@Entity
@DiscriminatorValue("student")
public class Student extends Person {
......
}
@Entity
public class Account {
......
@OneToOne
Person person;
}
这样做的好处是,Account只需持有Person的引用,在实际业务中只需要通过account.getPerson() instanceof Student这样的方法就能够判断出账号对应的身份。
但如果需要找出所有学生的账号该怎么办?因为一对一的关联是单向的,所以只能对Account进行条件查询。我们当然希望通过from Account a where a.person instanceof Student这样的HQL来查出来,但HQL中并没有instanceof这样的功能。
其实答案很简单:from Account a where a.person.class = "student"