Hello!
I have an entity with a lazy @Formula field:
Code:
private Integer commentCount;
@Formula("(SELECT count(c.id) from Comment c where c.post_id = id)")
@Basic(fetch=FetchType.LAZY)
public Integer getCommentCount() { return commentCount; };
In one scenario I would like to list all entities with comment counts.
Code:
select p from Post p WHERE p.forum = ? order by p.created desc
I would like the SQL generated to be:
Code:
SELECT p.id, p.topic, (...), (SELECT count(c.id) from Comment c where c.post_id = id) FROM..
but instead, the comment count is queried for in following SELECT calls, leading to N+1 problem.
I know I could use FetchType.EAGER, but I don't want to always fetch the commentCount. I don't want to use fetch all properties, because I have other properties/formulas in the entity, which I don't want to eagerly fetch at this time.
I have tried to use Hibernate Criteria API with FetchType.JOIN, SELECT and DEFAULT, and all failed to prefetch commentCount
How should I handle this problem? Could it be, that HQL has weaker expressiveness then Criteria API? This seems a major limitation (because it lacks flexibility in regard to fetching @Formula's).
Thanks,
Marcin Koziej