Hibernate Criteria API 过滤集合属性
我
Class A{
List <B> bList
}
Class B {
String name;
}
现在想使用 Hibrnate criteria API 编写查询,这样我就只能得到 A pojo 和经过过滤的 bList 属性,其中只有 B pojo
where "b.name" == 'abc'
I have
Class A{
List <B> bList
}
Class B {
String name;
}
Now I want to write query using Hibrnate criteria API , so that I only get A pojo's with a filtered bList property having only B pojo's
where "b.name" == 'abc'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一件非常危险的事情,虽然 Hibernate 支持它,但 JPA 不支持它,因为它加载的实体并不反映数据库中存储内容的真实情况。如果您碰巧修改了 B 列表,Hibernate 可能会删除所有与 A 相关但尚未被查询加载的 B。
也就是说,这是一个带有获取模式的简单内部联接:
This is a very dangerous thing to do, and although it's supported by Hibernate, it's not by JPA, because the entities that it loads do not reflect the reality of what is stored in the database. If you happen to modify the list of Bs, Hibernate might delete all the Bs that balong to the A, but which have not been loaded by the query.
That said, this is a simple inner join with a fetch mode:
我已经尝试过上面的代码,在我看来它没有过滤 B 集合。
我最终做的是在 A 类添加额外的过滤器
,然后使用 setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
要获得不同的 A 类,
它会向数据库查询 2 次,可能并不理想。如果还有其他选择,请纠正我。
I've tried the code above and it seems to me that it doesn't filter the B collection.
What I finally did is adding additional filter at class A
and then I use
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
to get distinct A class
It queries 2 times to DB and might not be desirable. Do correct me if there are any other alternatives.