Search code examples
jpapersistencethread-safetydaofetching-strategy

Is there a way to change the JPA fetch type on a method?


Is there a way to change the JPA fetch type on a single method without editing the entity object?

I have a shared ORM layer consisting of JPA entity classes. This ORM layer is accessed by two DAO layers. One DAO needs lazy fetching, as it is for my web application, the other needs eager fetching, as I need it to be threadsafe.

Here is an example method from my threadsafe DAO,

@PersistenceContext(unitName = "PersistenceUnit", type = PersistenceContextType.TRANSACTION)
private EntityManager em;

public ErrorCode findErrorCodeById(short id) {
    return (ErrorCode) em.createNamedQuery("ErrorCode.findById").
            setParameter("id", id).getSingleResult();
}

How would I make this method (or entire class) use eager fetching?


Solution

  • I assume that your entity associations (@OneToOne, @OneToMany, @ManyToOne) are fechted lazy (FetchType.Lazy)

    Then I can think of two ways:

    A. write two jpa query one which fetch the association of the lazy (thats the default way for hibernate) and a second query which explicit force eager loading of association (see "fetch" keyword in query).

            Query q = HibernateUtil.getSessionFactory().getCurrentSession()
                    .createQuery("select c from Category as c" +
                            " left join fetch c.categorizedItems as ci" +
                            " join fetch ci.item as i");
    
    
    

    B. use Hibernate.initialize(entity) to force eager loading of lazy relations of an entity after you have retrieved it (e.g. through finder ...)

    ErrorCode lazyCode = findErrorCodeById(1);
    // eager load associations
    Hibernate.initialize(lazyCode);