java - Criteria eager fetch-joined 集合以避免 n+1 选择

标签 java hibernate hibernate-criteria

假设 Item 和 Bid 是实体:一个 Item 有很多 Bids。它们以典型的父/子关系映射到 Hibernate 中:

<class name="Item" table="ITEM">
  ...
  <set name="bids" inverse="true">
    <key column="ITEM_ID"/>
    <one-to-many class="Bid"/>
  </set>
</class>

在执行此查询后尝试访问每个项目的出价时,如何避免 n+1 选择?

List<Item> items = session.createCriteria(Item.class)
                        .createAlias("bids", "b").
                        .add(Restrictions.gt("b.amount", 100)).
                        .list();

注意我需要一个eager fetching出价但对集合有进一步的限制(b.数量 > 100)

我试过以下方法失败了:

List<Item> items = session.createCriteria(Item.class)
                        .setFetchMode("bids", FetchMode.JOIN).
                        .createAlias("bids", "b").
                        .add(Restrictions.gt("b.amount", 100)).
                        .list();                        

List<Item> items = session.createCriteria(Item.class)
                        .createCriteria("bids")
                        .add(Restrictions.gt("amount", 100)).
                        .list();                        

最佳答案

这个条件查询似乎是正确的:

  List<Item> items = session.createCriteria(Item.class)
                    .setFetchMode("bids", FetchMode.JOIN)
                    .createAlias("bids", "b")
                    .add(Restrictions.gt("b.amount", 100))
                    .list();

FetchMode.JOIN 是为了解决n+1 问题。您是否定义了一些default_batch_fetch_size | batch-size 映射或配置中的任何位置,这是反向影响?

如果没有,你能试试下面的 HQL 看看这能解决你的问题吗?

 Query query = 
      session.createQuery("from Item it left join it.bids b where b.amount=:bids");
 query.setParamter(bids, 100);
 List<Item> items = query.list();

关于java - Criteria eager fetch-joined 集合以避免 n+1 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790080/

相关文章:

java - JPA Hibernate实体异常: org. hibernate.MappingException

java - 如何使用 hibernate 标准对子对象应用 DISTINCT

java - 如何将谓词列表添加到 CriteriaBuilder.or

java - LINQ(或 linq)是一个利基工具,还是正在成为基础工具?

java - RabbitMQ 服务器 bundle 分发 : Maven pom configuration

java - Grails hibernate 方言

java - Jackson hibernate 模块 - 渴望特定请求

java - 执行 SQL 的标准是什么?

java - 方法未按时间顺序调用

java - "Invalid byte 1 of 1-byte UTF-8 sequence"读取 RSS 源时