开发者

Restrict the class of an association in a Hibernate Criteria query

I have an object, 'Response' that has a property called 'submitter'. Sub开发者_开发问答mitters can be one of several different classes including Student, Teacher, etc...

I would like to be able to execute a criteria query where I select only responses submitted by teachers - so this means putting a class restriction on an associated entity. Any ideas on this? I'd like to stay away from direct SQL or HQL.


According to Gavin King, the following works with HQL:

where foo.class in (...)

Have you tried

c.createCriteria("submitter").add(Restrictions.eq("class", Teacher.class))

?


I ended up using native SQL. Not the greatest, but it isn't horrible either:

Criteria c = session.createCriteria(Response.class);
c.createCriteria("submitter").add(Restrictions.sqlRestriction("{alias}.person_type='student'"));

It's worth noting that this only worked because I was using the table-per-inheritance-hierarchy mapping strategy. Without that, I wouldn't have had a discriminator column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜