Retrieving Polymorphic Hibernate Objects Using a Criteria Query

冷暖自知 提交于 2019-12-03 10:44:23

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?

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:

14.9. The where clause

...

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

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"));

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.

Note that this also works for Joined Subclass inheritance mappings, with one caveat. The class used in the Restriction must be a concrete class. If you have a model like Animal <- Mammal <- Cat, you cannot do Restrictions.eq("class", Mammal.class); and expect to get back all Mammals. Instead, I had to brute force it using Restrictions.or with all known concrete classes (using Restrictions.in() gave a class cast exception when executing the query).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!