使用条件查询检索多态休眠对象 [英] Retrieving Polymorphic Hibernate Objects Using a Criteria Query

查看:33
本文介绍了使用条件查询检索多态休眠对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,我有一个抽象的用户"类,以及多个子类,例如申请人、HiringManager 和面试官.它们在一个表中,我有一个 DAO 来管理它们.

In my model I have an abstract "User" class, and multiple subclasses such as Applicant, HiringManager, and Interviewer. They are in a single table, and I have a single DAO to manage them all.

用户:

@Entity
@Table(name="User")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="role",
    discriminatorType=DiscriminatorType.STRING
)
public abstract class User extends BaseObject implements Identifiable<Long> ...

招聘经理(例如):

@Entity
@DiscriminatorValue("HIRING_MANAGER")
public class HiringManager extends User ...

现在,如果我想获得所有与部门无关的招聘经理,我该怎么做?我想它看起来像:

Now if I wanted to, say, get all the hiring managers that are not associated with a department, how would I do that? I imagine it would look something like:

DetachedCriteria c = DetachedCriteria.forClass(User.class);
c.add(Restrictions.eq("role", "HIRING_MANAGER"));
c.add(Restrictions.isNull("department"));
List<User> results = getHibernateTemplate().findByCriteria(c);

但是当我运行它时,Hibernate 抱怨无法解析属性:角色"(这实际上是有道理的,因为 User 类确实没有明确的角色属性)
那么做我想做的事情的正确方法是什么?

But when I run this, Hibernate complains "could not resolve property: role" (Which actually makes sense because the User class really doesn't have an explicit role property)
So what's the right way to do what I'm trying to do?

推荐答案

我可能遗漏了一些明显的东西,但是既然你想找到招聘经理,为什么不把 HiringManager 子类传递为Criteria 的类?

I may be missing something obvious but since you want to find hiring managers, why don't you just pass the HiringManager subclass as the class to the Criteria?

以防万一,有一个特殊的 class 属性可用于将查询限制为子类型.来自 Hibernate 参考文档:

Just in case, there is a special class property that you can use to restrict a query to a subtype. From the Hibernate reference documentation:

...

class 访问的特殊属性实例的鉴别器值在多态的情况下坚持.Java 类名嵌入 where 子句将是翻译成它的鉴别器值.

The special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.

from Cat cat where cat.class = DomesticCat

您也可以将这个特殊的类属性与 Criteria API 一起使用,但需要做一些小改动:您必须使用 鉴别器值 作为值.

You can use this special class property with the Criteria API too, but with a minor change: you have to use the discriminator value as value.

c.add(Restrictions.eq("class", "HIRING_MANAGER"));

与 HQL 不同,Hibernate 似乎没有使用 Criteria API 进行翻译.我真的不喜欢在代码中使用鉴别器值的想法,也许还有另一种更清洁的方法,但我不知道.但它有效.

Unlike with HQL, it looks like Hibernate is not doing the translation with the Criteria API. I don't really like the idea of using the discriminator value in the code and there is maybe another cleaner way but I'm not aware of it. But it works.

这篇关于使用条件查询检索多态休眠对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆