java 如何在没有直接链接到两个表的情况下对左外连接使用休眠条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1504592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How use hibernate criteria for a left outer join without direct link into the two tables
提问by
I'm trying to translate a SQL quest into Hibernate criteria.
我正在尝试将 SQL 任务转换为 Hibernate 标准。
My quest is working in SQL :
我的任务是在 SQL 中工作:
select * from objective
left outer join conditionstate
on objective.conditionid = conditionstate.conditionid
and conditionstate.personid = XXXX
where objective.toto_id = YYYYY
The objective is not directly mapped to the condition_state, but into a condition.
目标不是直接映射到条件状态,而是映射到条件。
objective --> condition <-- condition_state
I've tested something like :
我已经测试过类似的东西:
final DetachedCriteria criteriaObjective =
DetachedCriteria.forClass(Objective.class);
criteriaObjective.createAlias("conditionState", "conditionState", Criteria.LEFT_JOIN);
without success..
没有成功..
回答by ChssPly76
It's hard to suggest something without seeing your actual mappings. Going by your explanation and assuming that both condition and conditionState are mapped as many-to-one, you'd write something like:
如果没有看到您的实际映射,很难提出建议。根据您的解释并假设条件和条件状态都映射为多对一,您将编写如下内容:
final DetachedCriteria criteriaObjective =
DetachedCriteria.forClass(Objective.class);
criteriaObjective
.createCriteria("condition", Criteria.LEFT_JOIN)
.createCriteria("conditionState", Criteria.LEFT_JOIN)
.add(Restrictions.eq("personid", "XXXX") );
criteriaObjective.add(Restrictions.eqProperty("toto_id", "YYYY") );
Note that the above is NOTequivalent to the SQL query you've provided because "personid" condition will be generated as part of "WHERE" clause. As far as I know it's impossible to do a left join with condition using Criteria API - you may need to use HQL instead which provides with keywordfor that exact purpose:
请注意,上述内容不等同于您提供的 SQL 查询,因为“personid”条件将作为“WHERE”子句的一部分生成。据我所知,不可能使用 Criteria API 对条件进行左连接 - 您可能需要使用 HQL 来代替它为该确切目的提供关键字:
select o from objective as o
left join o.condition as c
left join c.conditionState as cs
with cs.person_id = 'XXXX'
and o.toto_id = 'YYYY'

