Hibernate的Criteria API还不支持嵌套关系吗
我想使用 Hibernate 的 Criteria API 来实现每个人所说的最可能的用例,即应用复杂的搜索条件。 问题是,我想要查询的表并不完全由原始值组成,而是部分由其他对象组成,并且我需要查询这些对象的 id。
我发现 这篇文章表明这是不可能的。 这是我尝试的方法,但没有成功,Hibernate 还有其他方面,我知道在字符串文字中支持这种点符号来指示对象嵌套。
if (!lookupBean.getCompanyInput().equals("")) {
criteria.add(Restrictions.like("company.company", lookupBean.getCompanyInput() + "%"));
}
编辑:
这是我正确分解的代码,用于完成我上面尝试的操作,使用下面第一个答案中的建议; 请注意,我什至使用额外的 createCriteria 调用来对另一个关联对象/表中的属性进行排序:
if (!lookupBean.getCompanyValue().equals("")) {
criteria.createCriteria("company").add(
Restrictions.like("company", lookupBean.getCompanyValue() + "%"));
}
List<TrailerDetail> tdList =
criteria.createCriteria("location").addOrder(Order.asc("location")).list();
I'd like to use Hibernate's Criteria API for precisely what everybody says is probably its most likely use case, applying complex search criteria. Problem is, the table that I want to query against is not composed entirely of primitive values, but partially from other objects, and I need to query against those object's id's.
I found this article from 2 years ago that suggests it's not possible. Here's how I tried it to no avail, there are other aspect of Hibernate where I know of where this sort of dot notation is supported within string literals to indicate object nesting.
if (!lookupBean.getCompanyInput().equals("")) {
criteria.add(Restrictions.like("company.company", lookupBean.getCompanyInput() + "%"));
}
EDIT:
Here's my correctly factored code for accomplishing what I was trying above, using the suggestion from the first answer below; note that I am even using an additional createCriteria call to order on an attribute in yet another associated object/table:
if (!lookupBean.getCompanyValue().equals("")) {
criteria.createCriteria("company").add(
Restrictions.like("company", lookupBean.getCompanyValue() + "%"));
}
List<TrailerDetail> tdList =
criteria.createCriteria("location").addOrder(Order.asc("location")).list();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不完全确定我遵循您的示例,但肯定可以在关联实体上指定过滤条件,只需嵌套 Criteria 对象来形成树即可。 例如,如果我有一个名为 Order 的实体,与 User 实体具有多对一关系,我可以通过查询查找名为 Fred 的用户的所有订单像这样:
如果您正在谈论一个与其自身有关系的实体,那么它也应该有效。 如果需要过滤关联对象的 ID,您还可以将“name”替换为“id”。
Not entirely sure I follow your example, but it's certainly possible to specify filter conditions on an associated entity, simply by nesting Criteria objects to form a tree. For example, if I have an entity called Order with a many-to-one relationship to a User entity, I can find all orders for a user named Fred with a query like this:
If you're talking about an entity that has a relationship to itself, that should work as well. You can also replace "name" with "id" if you need to filter on the ID of an associated object.