CFL_Jeff
CFL_Jeff

Reputation: 2719

How can I initialize lazy associations using Spring Data JPA when the query is specified in @Query annotation?

Here's my query before I converted over to Spring Data JPA. Notice how I used to use Hibernate.initialize() to manually fetch the widget's messages.

public Object findWidget(final Widget findMe) {
    Widget widget = getJpaTemplate().execute(new JpaCallback<Widget>() {
        public Widget doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createQuery("SELECT h FROM " + entityClass.getName() + " h where h.widgetId = ? ");
            q.setParameter(1, findMe.getId());

            Widget found = (Widget)q.getSingleResult();

            //Initialize lazy associations
            if(found!= null){
                Hibernate.initialize(widget.getMessages());
            }

            return found;
        }
    });
    return widget;
}

And here's what my query function looks like now. Notice there is no body to put the Hibernate.initialize() in.

@Query("SELECT h FROM Widget h where h.widgetId = ?1 ")
public AccessPoint findWidget(String widgetId);

So how can I specify that the widget's messages are to be fetched actively and not lazily?

Upvotes: 1

Views: 3975

Answers (2)

CFL_Jeff
CFL_Jeff

Reputation: 2719

Soon after I posted this question, I realized that I am trying to put functionality into the DAO layer that really belongs in the service layer.

So now I initialize the lazy associations using Hibernate.initialize(widget.getMessages()) in my WidgetService class, after I call WidgetDAO.findWidget().

I really should have been doing it this way all along.

EDIT: @MikeN has a good point. A fetch join is the real answer since it is implementation-independent and gets all necessary information in the original query.

Upvotes: 0

MikeN
MikeN

Reputation: 907

Try a fetch join, something like this:

@Query("SELECT h FROM Widget h LEFT JOIN FETCH h.messages WHERE h.widgetId = ?1 ")
public AccessPoint findWidget(String widgetId);

http://docs.oracle.com/html/E24396_01/ejb3_langref.html#ejb3_langref_fetch_joins

Upvotes: 5

Related Questions