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.
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. 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. The alias translates to the join clause when the SQL is generated. 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. (may not be a big deal depending on what version of what database you're using)
链接地址: http://www.djcxy.com/p/6318.html上一篇: Hibernate:Criteria按实体查询子对象(关联)(不是Id)
下一篇: 如何在休眠条件中添加“on”子句?