views:

34

answers:

2

I have an object, 'Response' that has a property called 'submitter'. Submitters 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.

A: 

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.

D Lawson
+1  A: 

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

?

meriton
yes, I tried your second one as well as the less-elegant `c.createCriteria("submitter").add(Restrictions.in("class",new Class[]{CommunityHealthWorker.class}));` just because Gavin said "where foo.class in"
D Lawson
And did it work? Oh, and Gavin probably used `in` rather than `eq` because instanceof also accepts subtypes, but eq doesn't. So if teachers were abstract, and either RegularTeacher or SubstituteTeacher, you'd need `in(RegularTeacher.class, SubstituteTeacher.class)` to express `instanceof Teacher`.
meriton