为什么这个HQL查询看起来不应该工作?

时间:2014-05-02 11:19:41

标签: java sql hibernate hql

对于以下对象:

class UserEntity {
  UUID id;
  private List<TeamEntity> teams = new ArrayList<TeamEntity>();
  private List<RuleEntity> rules = new ArrayList<RuleEntity>();
  ...

}

class RuleEntity {
  UUID id;
  private TeamEntity ownerTeam;
  private List<UserEntity> users = new ArrayList<UserEntity>(); 
  ...
}

Class TeamEntity {
  UUID id;
  private List<UserEntity> users = new ArrayList<UserEntity>();
  private List<RuleEntity> rules = new ArrayList<RuleEntity>();
}

如果我执行以下HQL查询,它会完成而不会出现错误并返回正确的结果:

select count(ruleEntity) from RuleEntity ruleEntity where :userId in elements(ruleEntity.users) and ruleEntity.ownerTeam.id = :teamId

但是,我不明白这个位是如何工作的:

where :userId in elements(ruleEntity.users)

对我来说,这是检查userID(这是一个UUID)是否存在于集合ruleEntity.users中,这是一个UserEntity列表,所以我会失败,因为它在一个UserEntity对象列表中检查了UUID对象?

1 个答案:

答案 0 :(得分:1)

它选择所有包含用户列表的ruleEntities,并且至少有一个用户列表包含:userId param

用SQL术语

FROM rule_entity
WHERE :userId in (select user_id
                  from rule_entity_users
                  where rule_entity.rule_id=rule_entity_users.rule_id)