简体   繁体   English

Hibernate标准,投影不执行@OneToMany映射的查询

[英]Hibernate criteria with projection not performing query for @OneToMany mapping

I have a domain object, Expense, that has a field called initialFields . 我有一个域对象Expense,它有一个名为initialFields的字段。

It's annotated as so: 它的注释如下:

@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JoinTable(blah blah)
private final List<Field> initialFields;

Now I'm trying to use Projections in order to only pull certain fields for performance reasons, but when doing so the initialFields field is always null. 现在我正在尝试使用Projections以便仅出于性能原因而拉出某些字段,但是这样做时,initialFields字段始终为null。 It's the only OneToMany field and the only field I am trying to retrieve with the projection that is behaving this way. 它是唯一的OneToMany字段,也是我尝试使用这种方式进行检索的唯一字段。 If I use a regular HQL query initialFields is populated appropriately, but of course I can't limit the fields. 如果我使用常规HQL查询,则会正确填充initialFields,但我当然不能限制字段。

Partial projection code: 部分投影代码:

Criteria criteria = session.createCriteria(Payment.class);
criteria.createAlias("expense", "e");

ProjectionList properties = Projections.projectionList();
//Some restrictions and more fields
properties.add(Projections.property("e.initialFields"), "initialFields");
criteria.setProjection(properties);
criteria.setFetchMode("e.initialFields", FetchMode.JOIN);
criteria.setReadOnly(true);
criteria.setResultTransformer(Transformers.aliasToBean(Expense.class));

return criteria.list();

When I turn on debugging and turn on show sql, the query to pull the initialFields doesn't appear to be created/run. 当我打开调试并启用show sql时,拉出initialFields的查询似乎没有创建/运行。 Anyone ever seen anything like this? 有没有见过这样的人?

I've just tried using HQL projection, by specifying each field I want to pull and then manually building the object. 我刚刚尝试使用HQL投影,通过指定我要拉的每个字段然后手动构建对象。 In this case the SQL built by Hibernate is incorrect for the initialFields field. 在这种情况下,Hibernate构建的SQL对于initialFields字段是不正确的。 expense1_.name as col_1_0_, . as col_2_0_, expense1_.account_id as col_3_0_ expense1_.name as col_1_0_, . as col_2_0_, expense1_.account_id as col_3_0_ . expense1_.name as col_1_0_, . as col_2_0_, expense1_.account_id as col_3_0_ The . as col_2_0_ is . as col_2_0_ is . as col_2_0_ is where the initialFields would be pulled. . as col_2_0_ is初始字段将被拉出的位置。 My guess is that it should be expense1_.id as col_2_0_ . 我的猜测是它应该是expense1_.id as col_2_0_

Edit: I just removed the Result Transformer to inspect each property and the initialFields property is indeed null. 编辑:我刚刚删除了Result Transformer以检查每个属性,而initialFields属性确实为null。

I had similar problem and for me was working explicitly specifying joinType in criteria. 我有类似的问题,对我来说是明确指定条件中的joinType

Criteria criteria = session.createCriteria(Payment.class);
criteria.createAlias("expense", "e", CriteriaSpecification.LEFT_JOIN);

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

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