提问人:user2687644 提问时间:5/7/2014 最后编辑:Stanislovas Kalašnikovasuser2687644 更新时间:5/18/2020 访问量:744
JPQL 构造函数表达式,如何在“select new”中急切地获取主实体
JPQL Constructor Expressions, how to eagerly fetch the main entity in 'select new'
问:
我的原始查询有些复杂,但我尝试做的是获取实体 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
另一种方法是选择表的每一列,这是我想避免的。
答:
-1赞
jaudo
9/12/2015
#1
你可以通过以下命令让 hibernate 抓取广告:
JOIN FETCH ac.alertDefinition ad
0赞
fuminchao
5/18/2020
#2
面临同样的问题。
我不知道如何让休眠获取。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());
评论