Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate query - How to select those parents that have ALL the children matching a value?

I'm trying to write a Hibernate (JPA) query to select those parents where ALL their children match a property.

Let's make a pratical example...

I want to select those fathers who have ALL their children blond. If just one is black haired the father is not selected.

How will the query look like? Thank you in advance!

like image 783
Andrea T Avatar asked Oct 16 '12 19:10

Andrea T


3 Answers

Maybe something like this will work:

From Father f
where not exists (select c from f.children c where not c.hair = "BLONDE");

Just an idea...

like image 149
Andrea T Avatar answered Nov 15 '22 07:11

Andrea T


Try this using the ALL see http://openjpa.apache.org/builds/1.1.0/docs/jpa_langref.html#jpa_langref_all_any:

select p from parent where 'blonde'=all(parent.children.haircolor)
like image 25
jabal Avatar answered Nov 15 '22 07:11

jabal


This should also work and it looks a bit cleaner.

SELECT p from Parent p join p.children c where c.haircolor = 'blonde';
like image 35
Kainda Avatar answered Nov 15 '22 09:11

Kainda