1

我写的

    String sql = "select candidate_skill.candidate_id from candidate_skill " +
            "inner join skill on  skill.id = candidate_skill.skill_id  " +
            "where skill_id in (:skillIdList) group by candidate_skill.candidate_id " +
            "Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in (:skillIdList) )";
    sql = sql.replace(":skillIdList", generateSkillIdList(skills));
    Query query = session.createSQLQuery(sql);
    List<Candidate> candidates = query.list();

效果很好

第二种情况:

    String sql = "select candidate_skill.candidate_id from candidate_skill " +
            "inner join skill on  skill.id = candidate_skill.skill_id  " +
            "where skill_id in :skillIdList group by candidate_skill.candidate_id " +
            "Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in :skillIdList )";
    Query query = session.createSQLQuery(sql).setParameterList("skillIdList", skills);
    List<Candidate> candidates = query.list()

日志:

Hibernate: select candidate_skill.candidate_id from candidate_skill inner join skill on  skill.id = candidate_skill.skill_id  where skill_id in (?, ?) group by candidate_skill.candidate_id Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in ?, ? )

它不起作用

第三:

String sql = "select candidate_skill.candidate_id from candidate_skill " +
                "inner join skill on  skill.id = candidate_skill.skill_id  " +
                "where skill_id in :skillIdList group by candidate_skill.candidate_id " +
                "Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in (:skillIdList) )";
        Query query = session.createSQLQuery(sql).setParameterList("skillIdList", skills);
        List<Candidate> candidates = query.list();

日志:

Hibernate: select candidate_skill.candidate_id from candidate_skill inner join skill on  skill.id = candidate_skill.skill_id  where skill_id in (?, ?) group by candidate_skill.candidate_id Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in (?, ?) )

效果很好

PS注意周围的括号:skillIdList

如果我在查询中使用 setParameterList("argument",value) 和参数 2 次,那么第一次休眠替换括号,第二次 - 无

4

1 回答 1

2

的语法IN需要括号。

至于为什么第三个例子有效,有两个猜测:

  • hibernate 具有自动附加缺少的括号的功能,但不知何故这并没有扩展到子查询
  • sql server首先执行子选择,然后另一个查询与您传递的参数变得多余,因此不会执行。
于 2013-08-12T13:29:52.643 回答