Find instance with at least one instance of a specified type in associated collection
I have an existing domain at work and haven't been able to limit the result of a query based on at least one instance of a specified type in an associated collection.
For example:
Say a Person has a one-to-many association to Pet. Pet is abstract and has several subclasses such as Bird, Cat, Dog, etc. and is mapped using the table-per开发者_运维问答-class-hierarchy mapping strategy.
How would one write a query in hql to return all the Person instances that has at least one associated Dog?
Since the Pets are on the 'many' side, they probably point back to their respective Person entities. That means you can just select on unique(Person) in the Pets table where person is not null. Since you are using table-per-class-hierarchy, there is a discrimator column, so you can discriminate on the type, which is '.class'.
String hql = "select unique(p.person) from Pet p where p.class = ? and p.person is not null"
and then execute the query using positional parameters -- i.e. replace the ? with DOG or CAT or whatever. Note that i made up field names, so you will have to replace them with your actual values.
精彩评论