How can I write a Hibernate Criteria query, for a super-class, and check for a certain sub-class?

冷暖自知 提交于 2019-12-04 07:22:11

It's really not clear what you want to do.

First of all, since Foo inherits from Bar, searching for Bar instances will automatically return Foo instances. Hibernate takes care of joining the tables by itself.

Second: your SQL query is really strange. You're doing a left join (which means that you're searching for bars who might not have an associated foo), but you also have a where close on foo.bar_id being not null. This in fact constitutes an inner join, and could be rewritten as

select b.* from bar b inner join foo f on f.bar_id = b.id

If what you want to do is search for Foos, and Foos only, then use a Criteria with Foo as root entity:

getSession()
    .createCriteria(Foo.class)
    .list();

You will get Foo instances, but since Foo extends Bar, these Foo instances are also Bar instances. That's what inheritance is.

Now if you're building your Criteria instance dynamically, and realize at some point that the search must only return instances of Foo, you have to use the implicit class property:

Criteria c = getSession().createCriteria(Bar.class, "bar")
// ...
if (limitToFoos) {
    c.add(Restrictions.eq("bar.class", Foo.class));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!