I need to eager fetch a lazy collection with Criteria. The JPA book seems to indicate that I can use FetchMode.JOIN to override laziness on a collection and force it to load. This doesn't seem to be working for my example below:
Mapping file
Code:
<hibernate-mapping auto-import="true" default-lazy="true" package="com.orders" >
<class name="Customer" table="customers">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<set name="phones" table="customer_phone" cascade="all" lazy="true"">
<key column="customer_id" />
<many-to-many column="phone_id" class="Phone" />
</set>
</class>
<class name="Phone" table="phones">
<id name="id">
<generator class="native" />
</id>
<property name="number" />
<property name="type" />
<set name="customers" inverse="true" table="customer_phone">
<key column="phone_id"/>
<many-to-many column="customer_id"
class="Customer"/>
</set>
</class>
</hibernate-mapping>
Unit test
Code:
public void testFetchPhonesEager() throws Exception
{
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria( Customer.class, "customer" )
.add( Restrictions.idEq( 1l ) )
.createAlias( "phones", "p")
.setFetchMode( "p", FetchMode.JOIN );
List<Customer> customers = criteria.list();
Set<Customer> customerSet = new HashSet<Customer>(customers);
// uncomment these two lines and everything works fine
// for (Customer customer : customers)
// Hibernate.initialize( customer.getPhones() );
session.close();
final Customer customer = customers.get( 0 );
// Problem: LazyInitializationException is thrown!!!
assertTrue(customer.getPhones().size() == 3);
}