我需要一种方法来做所有"在所有" Grails / Hibernate中的条件查询。标准" in"限制是我称之为"在任何"限制。
举例来说......
序言
参加域名课程" Knights"与另一个域类具有多对多关联" Perils"。课程很简单......
class Knight {
String name
static hasMany = [perils:Peril]
}
class Peril {
String name
static hasMany = [knights:Knight]
static belongsTo = Knight
}
表格内容如下所示......
Knights 1 Arthur, King of the Britains (Not technically a knight. I know, I know.) 2 Sir Bedevere the Wise 3 Sir Lancelot the Brave 4 Sir Robin the Not-Quite-So-Brave-As-Sir-Lancelot 5 Sir Galahad the Pure Perils 1 Black Knight 2 Knights who say Ni 3 Three-Headed Giant 4 Swamp Castle 5 Castle Anthrax 6 Rabbit of Caerbannog Knights_Perils 1, 1 // arthur fights the black knight 1, 2 // arthur fights the knights who say ni 2, 2 // bedevere fights the knights who say ni 4, 3 // Robin runs-away from Three-Headed Giant 3, 4 // Lancelot Assaults Swamp Castle 5, 5 // Galahad visits Castle Anthrax 3, 5 // Lancelot "rescues" Galahad from Castle Anthrax 1, 6 // All Knights fight the Killer Bunny 2, 6 // ... 3, 6 // ... 4, 6 // ... 5, 6 // ...
我提供了一个表单,提供了搜索关联的复选框......
Choose Perils and Search for Knights... [ ] Black Knight (id 1) [ ] Knights who say Ni (id 2) [ ] Three-Headed Giant (id 3) [x] Swamp Castle (id 4) [x] Castle Anthrax (id 5) [x] Killer Bunny (id 6) [search]
我这样查询:
def query = Knights.createQuery()
query.list(max: params.max, offset: params.offset) {
if(params.perils) perils { 'in' ('id', params.list('perils')*.toLong()) }
}
这产生了我所说的"在任何"结果。骑士与任何"在任何"被检查的危险列表。在上述形式的3次检查中,所有骑士......
Arthur - fights bunny Bedevere - fights bunny Lancelot - swamp castle, castle anthrax, fights bunny Robin - fights bunny Galahad - castle anthrax, fights bunny
问题
我正在寻找类似于"在"中的Hibernate / Grails标准限制。但这将在所有"中查询"。换句话说,奈特有一个协会"在所有"列表中已检查的危险。有了这个限制,以及上面输入的相同表格,我希望结果只是
Lancelot - swamp castle, castle anthrax, fights bunny
是否"在所有" Hibernate标准的版本" in"限制?
请记住,我想要使用CriteriaQuery(使用Hibernate或Grails方言),而不是直接使用SQL或HQL。
关于如何解决这个问题的任何指示?
谢谢!
答案 0 :(得分:1)
好问题。也许有更好的选择,因为我不知道SQL / HQL的每个方面,但是以下条款:
all the selected perils are in the knight's perils
也可以这样表达
there is no peril in the selected perils that is not in the knight's perils
因此,在HQL中,您可以这样表达:
select knight from Knight knight
where not exists (select peril.id from Peril peril
where peril.id in :selectedPerilIds
and peril.id not in (select peril2.id from Peril peril2
where peril2.knight.id = knight.id))