【问题标题】:JPQL Constructor Expressions, how to eagerly fetch the main entity in 'select new'JPQL 构造函数表达式,如何在“选择新”中急切地获取主要实体
【发布时间】:2014-06-23 19:00:47
【问题描述】:

我的原始查询有些复杂,但我想做的是获取实体 AlertCondition 以及一些附加字段。

    + "  SELECT new org.rhq.core.domain.alert.composite.AlertConditionEventCategoryComposite " //
    + "       ( " //
    + "         ac, " //
    + "         res.id " //
    + "       ) " //
    + "    FROM AlertCondition AS ac FETCH ALL PROPERTIES " //
    + "    JOIN ac.alertDefinition ad " //
    + "    JOIN ad.resource res " //
    + "   WHERE " + AlertCondition.RECOVERY_CONDITIONAL_EXPRESSION //
    + "     AND ( res.agent.id = :agentId OR :agentId IS NULL ) " //
    + "     AND ad.enabled = TRUE " //
    + "     AND ad.deleted = FALSE " //
    + "     AND ac.category = 'EVENT' " //
    + "ORDER BY ac.id"), //

问题是Hibernate只选择了AlertCondition的ID,所以当访问这个对象时,这最终需要N+1个选择,而我只想做1个。

select 只是获取 ID 列,根据调试:

select alertcondi0_.ID as col_0_0_, alertdefin1_.ID as col_1_0_, resource2_.ID as col_2_0_

我要返回的是 *AlertCondition 的所有字段。

我在 Hibernate 下找不到任何方法来执行此操作。 JOIN FETCH 在这里也不起作用。

另一种方法是选择表格的每一列,这是我想避免的。

【问题讨论】:

  • 您对此选择的查询要求是什么?您的 AlertCondition 实体的内容是什么?
  • 您好,是的,由于您使用的是自定义构造函数表达式,我们需要查看您的 AlertCondition 实体中是否存在匹配的构造函数

标签: sql hibernate select jpa


【解决方案1】:

面临同样的问题。 我也不知道怎么让hibernate获取ac.*。

但我找到了解决方法。

@Query("select ac, xxx, zzz")
List<Object[]> fetchRecords()

//
Constructor<?> constructor = AlertConditionEventCategoryComposite.class.getDeclaredConstructors()[0];
List<AlertConditionEventCategoryComposite> composites = fetchRecords.stream().map(constructor::newInstance).collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    您可以通过以下方式告诉 hibernate 获取广告:

    JOIN FETCH ac.alertDefinition ad
    

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2013-11-16
      • 1970-01-01
      • 2017-06-17
      • 2018-09-03
      • 2011-08-25
      • 2012-08-29
      • 2013-11-18
      相关资源
      最近更新 更多