简体   繁体   English

如何改善休眠查询?

[英]How to improve the hibernate query?

I have two classes which named A and B. The primary key of B is a field of tab_A. 我有两个名为A和B的类。B的主键是tab_A的字段。 The mapping xml is like: 映射xml类似于:

<hibernate-mapping>
    <class name="com.fabulous.A" table="tab_A">
        <id name="id" column="id">
            <generator class="assigned" />
        </id>
        <property name="userId" column="user_id" />

        <many-to-one name="B" column="B_id"
            class="com.fabulous.B" unique="true" lazy= "false" cascade="merge">
        </many-to-one>
    </class>
</hibernate-mapping>

And there is another mapping xml which mapping class B to table B. The query in my application is: 还有另一个映射XML,它将类B映射到表B。我的应用程序中的查询是:

session.createQuery("FROM A WHERE id IN (:ids)").setParameterList("ids", ids).list();

The parameter is a list of A.id. 该参数是A.id的列表。 The size of list is 100; 列表的大小为100;

When lazy=true the query time is about 1s , but about 1 minute will be cost when Ab is applied. lazy = true时,查询时间约为1s ,但是应用Ab时将花费大约1分钟的时间。 Actually B will always be required, so I close lazy loading. 实际上,总是需要B,因此我关闭了延迟加载。 And the query time is about 40s. 查询时间约为40s。

From hibernate log, hibernate load B from table B one by one but not in a batch. 从休眠日志中,一个一个地休眠休眠表B的负载B,但不是一个批次。 I think if I extract all B.id from table A in a query and then query table B within a batch the total time will be less than 3s. 我认为,如果我从查询中的表A中提取所有B.id,然后在一批中查询表B,则总时间将少于3s。

But it's not convenience, could anyone help to figure out how to improve the query with hibernate? 但这不是方便,任何人都可以帮忙弄清楚如何使用休眠模式改善查询吗?

Thanks a lot. 非常感谢。

要急切地获取查询的某些关系,只要该关系是可选的,只需执行简单的JOIN FETCHLEFT JOIN FETCH

FROM A a JOIN FETCH a.B WHERE a.id IN (:ids)

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

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