When I specify a restriction on an one-to-many association in a criteria query, Hibernate executes n+1 queries even though the first query is joining the two tables correctly with an inner join. This happens if I use createAlias or createCriteria to specify the restriction on the association. If I don't specify a restriction on the association then I do not get n+1 queries and the association is populated. Is there a way to avoid the n+1 queries when setting restrictions on associations?
Criteria Query: final DetachedCriteria criteria = DetachedCriteria.forClass(A.class); criteria.add(Restrictions.eq("column1", value1)) .createAlias("someSetofB", "h") .add(Restrictions.in("h.code", new String[] {"A","B","C"})); final List<A> list = getHibernateTemplate().findByCriteria(criteria);
Association Mapping: <set name="someSetofB" lazy="false" fetch="join"> <key> <column name="SOME_ID" /> </key> <one-to-many class="B" /> </set>
SQL: select ..(every column from A and B).. from A this_ inner join B h1_ on this_.SOME_ID=h1_.SOME_ID where this_.COLUMN_ONE=? and h1_.CODE in (?, ?, ?) select .... from B someSetOfB0_ where someSetOfB0_.SOME_ID=? select .... from B someSetOfB0_ where someSetOfB0_.SOME_ID=? ..... selects for as many A's returned by first query
|