Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate fetch with multiple associations

I am doing this for my lazy load collections on entity objects :

@Transactional(readOnly = true)
public T getWithAssociation(final long id, String association) {
    Session session = sessionFactory.getCurrentSession();
    final Criteria crit = session.createCriteria(genericType);
    crit.setFetchMode(association, FetchMode.JOIN);
    crit.add(Property.forName("id").eq(id));
    return (T) crit.uniqueResult();
}

I want to return an entity object with multiple lazy loaded collections loaded, can I do this (pass in a list and set more than association for a single criteria?) :

   @Transactional(readOnly = true)
    public T getWithAssociations(final long id, List<String> associations) {
        Session session = sessionFactory.getCurrentSession();
        final Criteria crit = session.createCriteria(genericType);
        for(String association:associations) {
            crit.setFetchMode(association, FetchMode.JOIN);
        }
        crit.add(Property.forName("id").eq(id));
        return (T) crit.uniqueResult();
    }
like image 776
NimChimpsky Avatar asked Jan 14 '13 21:01

NimChimpsky


1 Answers

Yes?

The docs contain the following:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .setFetchMode("mate", FetchMode.EAGER)
    .setFetchMode("kittens", FetchMode.EAGER)
    .list();

This query will fetch both mate and kittens by outer join. See Section 20.1, “Fetching strategies” for more information.

like image 135
digitaljoel Avatar answered Sep 29 '22 00:09

digitaljoel