简体   繁体   English

休眠查询优化

[英]Hibernate Query Optimization

I have a piece of code similar to the following: 我有一段类似于以下内容的代码:

  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
        }
    }
  }

Every time the for loop is executed it will run additional hibernate queries behind the scenes to pull the extra data (since the Objects are marked as lazy loaded). 每次执行for循环时,都会在后台运行其他休眠查询以拉出额外的数据(因为对象被标记为延迟加载)。 Switching those Objects to eager is not desired because other classes that use the POJO do not need that data. 不需要将那些对象切换为渴望对象,因为使用POJO的其他类不需要该数据。

Obviously the code above can create a bottleneck which is something I'd like to avoid. 显然,上面的代码会造成瓶颈,这是我想避免的。 Is there a hibernate-specific way (ie no native SQL) of modifying the query to bring back only the necessary data in one shot? 是否存在特定于休眠的方式(即没有本机SQL)来修改查询以仅一次拍摄仅带回必要的数据?

I'm fine with having the query return a String[][] with col1 as the key and col2 as the value instead of returning Foo 我可以让查询返回String [] [],而col1作为键,col2作为值,而不是返回Foo

Update: 更新:

I changed the query to just return the key/values necessary 我将查询更改为仅返回必要的键/值

"select distinct c.id, foo.someValue from ... “从...中选择不同的c.id,foo.someValue。

As I understand you question you don't want to have the collection eager by default but in these concrete case/method fetch all in one query?! 据我所知,您不希望默认情况下渴望集合,但是在这些具体情况/方法中,一次查询就可以获取所有信息吗?

Here is the fragment from hibernate documentation concerning this: 这是休眠文档中与此有关的片段:

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. 有关更多信息,请参见第19.1节“获取策略”。

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 http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM