简体   繁体   English

如何在休眠条件上添加“ on”子句?

[英]How to add a “on” clause on hibernate criteria?

DetachedCriteria criteria = DetachedCriteria.forClass(Parent.class,"parent");
criteria.createAlias("parent.child","thechild");
criteria.add(Restrictions.eq("thechild.property", "somevalue");

I read many sample code like above, here the criteria join two tables, parent and child, but I just don't know how/where to specify a On condition on the criteria. 我读了很多上面的示例代码,这里的条件将两个表(父表和子表)连接在一起,但是我只是不知道如何/在哪里在条件上指定On条件。

like the following 像下面

select * from parent inner join child on parent.childid = child.id

but in the criteria above, I just can not find where to add the on condition. 但在上述标准,我只是找不到在哪里添加on条件。 Should I set this in hibernate configuration file? 我应该在休眠配置文件中设置它吗? Is it possible to set in the query? 是否可以在查询中设置?

And how do I get content of all fields in the two table after join together? 连接在一起后,如何获取两个表中所有字段的内容? create a new class which contains all fields in both table? 创建一个包含两个表中所有字段的新类?

You don't need to specify the fields to join on because it is already specified in the table mapping. 您不需要指定要加入的字段,因为它已在表映射中指定。 For example: 例如:

<bag name="Children">  
   <key column="ParentId" />  
   <one-to-many class="Parent" />  
</bag>

'createAlias' is the addition of the 'on' clause. 'createAlias' 'on'子句的添加。 The alias translates to the join clause when the SQL is generated. 生成SQL时,别名会转换为join子句。 The query will return a List of Parent objects. 该查询将返回父对象列表。 Don't really follow what you mean by "get all the data from both tables." 不要真正按照您的意思“从两个表中获取所有数据”。 You'll have a list of Parent Objects with Child Objects. 您将具有一个带有子对象的父对象列表。 All the data is there represented the way you mapped it. 那里的所有数据都代表您映射它的方式。 If you want it represented in some other way, then yes you'll probably need to create a new object that has the specific data you want. 如果希望它以其他方式表示,则可能是的,您可能需要创建一个具有所需特定数据的新对象。

Which leads to an aside on performance, sometimes you see someone cut and paste a "standard" criteria that creates every possible alias then add what restrictions they need. 这会导致性能下降,有时您会看到有人剪切并粘贴了创建所有可能别名的“标准”条件,然后添加了他们所需的限制。 Don't do this! 不要这样! As soon as you do 'createAlias' there will be a join in your SQL whether you use the alias later or not. 一旦您执行“ createAlias”,无论您以后是否使用别名,SQL中都会有一个联接。 (may not be a big deal depending on what version of what database you're using) (根据您使用的数据库的哪个版本,可能没什么大不了的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM