我有以下2个JPA课程:
@Entity
public class AnalysisPolicy {
private Set rules;
//stuff omitted
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set getRules() {
return rules;
}
}
@Entity
public class AnalysisRule {
//stuff omitted
}
以及以下JPQL查询:
select p from AnalysisPolicy p, AnalysisRule r where r.id=:ruleId and r in p.rules
它接受一个java.util.UUID类型的单个参数ruleId(这就是我用作所有实体的@Id的类)。
尝试执行查询我得到以下结果:
Hibernate: /* select p from AnalysisPolicy p, AnalysisRule r where r.id=:ruleId and r in p.rules */ select analysispo0_.f_id as f1_12_, analysispo0_.f_lastmodified as f2_12_, analysispo0_.global as global12_ from AnalysisPolicy analysispo0_ cross join AnalysisRule analysisru1_ cross join AnalysisPolicy_AnalysisRule rules2_, AnalysisRule analysisru3_ where analysispo0_.f_id=rules2_.AnalysisPolicy_f_id and rules2_.rules_f_id=analysisru3_.f_id and analysisru1_.f_id=? and ( analysisru1_.f_id in ( . ) ) limit ? [org.hibernate.util.JDBCExceptionReporter] SQL Error: 0, SQLState: 42601 [org.hibernate.util.JDBCExceptionReporter] ERROR: syntax error at or near "."
这意味着我的JPQL被hibernate接受,但由于某种原因,它产生的SQL无效(“( - )中的”analyzeru1_.f_id“部分。)
我正在使用hibernate 3.6和postgresql 9作为数据库。 我做错了什么?
答案 0 :(得分:3)
查询错误,IN
不能以这种方式使用。你应该写
select p from AnalysisPolicy p, AnalysisRule r
where r.id=:ruleId and r in elements(p.rules)
或
select p from AnalysisPolicy p, AnalysisRule r
where r.id=:ruleId and r member of p.rules
但以下查询可能是最好的:
select p from AnalysisPolicy p join p.rules r where r.id=:ruleId
答案 1 :(得分:1)
你的HQL让我感到困惑。我想你可以改写它:
select r.p from AnalysisRule r where r.id=:ruleId
它将返回包含给定规则的所有策略。你甚至可以把它放在那里: - )
编辑:axtavt更快,并提供了比我更好的答案。似乎我们对重写HQL查询有类似的想法。