我有一段类似于以下的代码:
public void doQuery(final Baz baz){
final Query query = getSessionFactory().getCurrentSession().createQuery(
"select distinct foo from Foo as foo "+
"join foo.a as a"+
"join foo.b as b "+
"join b.c as c "+
"where baz=:baz"
);
query.setParameter("baz", baz);
final List<Foo> list = query.list();
for (final Foo foo : list) {
final Set<C> cSet = foo.getB().getCs();
final String value = foo.getSomeValue();
for (final C c : cSet) {
final Long key = c.getSomeLong();
// Do stuff with key and value
}
}
}
每次执行 for 循环时,它都会在幕后运行额外的 hibernate 查询来提取额外的数据(因为对象被标记为延迟加载)。将这些对象切换为 eager 是不需要的,因为使用 POJO 的其他类不需要该数据。
显然,上面的代码可能会造成瓶颈,这是我想避免的。是否有一种特定于 hibernate 的方法(即没有 native SQL)来修改查询以一次性仅返回必要的数据?
我可以让查询返回一个 String[][],其中 col1 作为键,col2 作为值,而不是返回 Foo
更新:
我将查询更改为仅返回必要的键/值
“从...中选择不同的 c.id, foo.someValue
最佳答案
据我了解,您的问题是您不希望默认情况下急切地收集集合,但在这些具体案例/方法中,在一个查询中获取所有内容?!
这是 hibernate 文档中与此相关的片段:
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 19.1, “Fetching strategies” for more information.
from Cat as cat
inner join fetch cat.mate
left join fetch cat.kittens
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
关于java - Hibernate 查询优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12007365/