Im trying to eagerly fetch all contentItems to avoid the N + 1 lazy initialization problem but my setfetchmode call gets ignored by hibernate when using projections. While not using projections it works as expected.
What am I doing wrong?
The contentItem is a custom object.
Session session = getSessionFactory().getCurrentSession();
Criteria criteria = session.createCriteria(Media.class);
criteria
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("fileName"), "fileName")
.add(Projections.property("mimeType"), "mimeType")
.add(Projections.property("contentItem"), "contentItem"))
.setFetchMode("contentItem", FetchMode.JOIN)
.setResultTransformer(Transformers.aliasToBean(Media.class));
criteria.addOrder(Order.asc("id"));
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
return criteria.list();
UPDATE: In addition to @NiVeR answer
Entity relationship fetch type still has not effect on outcome.
private ContentItem contentItem;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "content_item_id")
public ContentItem getContentItem() {
return this.contentItem;
}
And repositioning the setFetchMode like this also has no effect.
Session session = getSessionFactory().getCurrentSession();
Criteria criteria = session.createCriteria(Media.class);
criteria.setFetchMode("contentItem", FetchMode.JOIN);
criteria
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("fileName"), "fileName")
.add(Projections.property("mimeType"), "mimeType")
.add(Projections.property("contentItem"), "contentItem"))
.setResultTransformer(Transformers.aliasToBean(Media.class));
criteria.addOrder(Order.asc("id"));
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
return criteria.list();
Probably the behavior is explained by the line:
at this point to project the relation of this entity, Hibernate uses the FetchType defined in the entity where you defined the relation. So the FetchMode.JOIN that you add afterwards has no impact because it happens later.