fil*_*fku 4 java hibernate query-by-example hibernate-criteria
我想根据关联相关对象的值搜索我的数据源中的所有对象实例.数据模型可以简化为:类型A的对象包含类型B的对象列表.目标是查找A的所有实例,其中A包含B,使得B具有属性值X.
我已经可以使用Criteria查询成功实现此目的,如下所示:
List<A> results = session.createCriteria(A.class)
.createCriteria("listOfBs")
.add(Restrictions.eq("propertyInB", x))
.list();
Run Code Online (Sandbox Code Playgroud)
这是一种简化,B的多个属性将适用 - 搜索功能对于用户填充的过滤器是必需的.
我想通过示例查询替换这种方法 - 我只是创建一个具有所需参数的对象图.我在遵循Hibernate文档时的尝试失败了,并在此问题中进行了描述.
我认为以一种有效的方式展示我想要实现的东西,然后寻找等价物可能会有所帮助 - 这就是我重新提出这个问题的原因.
简而言之,我的问题是:如何在Hibernate中将上述Criteria Query实现为Query by Example?我正在使用Hibernate 3.6.6.
谢谢!
假设您想要执行以下操作:
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"
Run Code Online (Sandbox Code Playgroud)
使用Query by Example(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();
Run Code Online (Sandbox Code Playgroud)
结果已经是fetch-joined,这意味着A中的集合实例B已经完全初始化.
| 归档时间: |
|
| 查看次数: |
5502 次 |
| 最近记录: |