2011-11-23 102 views
3

我想根据关联关联的对象的值搜索我的数据源中的所有对象实例。数据模型可以简化为:类型A的对象保存类型B的对象的列表。目标是查找A的所有实例,其中A包含B使得B具有属性值X.休眠:按示例查询关联等效条件查询

I已经可以顺利实现这一使用条件查询如下:

List<A> results = session.createCriteria(A.class) 
    .createCriteria("listOfBs") 
    .add(Restrictions.eq("propertyInB", x)) 
    .list(); 

这是一种简化,和B的多个属性将适用 - 搜索功能是必要的用户填充过滤器。

我想用示例查询来替换这种方法 - 我只需用所需的参数创建一个对象图。我遵循Hibernate文档的尝试失败,并在this question中描述。

我认为这可能有助于证明我试图以一种有效的方式实现,然后寻求等价物 - 这就是为什么我重新提出这个问题的原因。

总之,我的问题是:你将如何在Hibernate中将上述Criteria Query作为示例的查询来实现?我正在使用Hibernate 3.6.6。

谢谢!

回答

5

假设你想要做的事,如:

Select a.* , b* 
from a join b on a.id = b.id 
where a.property1 = "wwww" 
and a.property2="xxxx" 
and b.property1="yyyy" 
and b.property2="zzzz" 

要实现使用实例查询(QBE)上面的查询:

/***Initialize an instance of Class A with the properties that you want to match***/ 
A instanceA = new A(); 
instanceA.setProperty1("wwww"); 
instanceA.setProperty2("xxxx"); 
Example exampleA = Example.create(instanceA); 

/***Do the same for the Class B**/ 
B instanceB = new B(); 
instanceB.setProperty1("yyyy"); 
instanceB.setProperty2("zzzz"); 
Example exampleB = Example.create(instanceB); 

/**Create and execute the QBE***/ 
List<A> results = session.createCriteria(A.class) 
    .add(exampleA) 
    .createCriteria("b",CriteriaSpecification.LEFT_JOIN) // b is the property of Class A 
    .add(exampleB) 
    .list(); 

结果已被取指令 - 加盟,这意味着A中的集合实例B已经完全初始化。

+0

谢谢你的答案肯。我试过这个,但碰到与我以前的问题相同的问题(http://stackoverflow.com/questions/7976491/hibernate-query-by-example-involving-one-to-many-relationship) - org.hibernate。 QueryException:无法解析属性:_com of B.您是否有任何想法可能会出错? –

+0

我现在不知道。通常情况下,如果你在代码中编写了一些无效的路径,例如'.createCriteria(“_ com”,CriteriaSpecification.LEFT_JOIN)','_com'不是你的实体的属性,那么'无法解析属性'会发生。 –

+0

不幸的是,_com不是我在任何地方定义的属性/字段,这对我不起作用。此外,_com不是我的工作区中包含的任何库中存在的属性名称。然而,这是文档建议我们为QBE所做的事情,因此我会将其标记为答案..我必须去似乎没有QBE。 –