在@Query批注中指定查询时,如何使用Spring Data JPA初始化惰性关联? [英] How can I initialize lazy associations using Spring Data JPA when the query is specified in @Query annotation?
本文介绍了在@Query批注中指定查询时,如何使用Spring Data JPA初始化惰性关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的查询之前,我转换为Spring Data JPA.请注意,我以前是如何使用Hibernate.initialize()
手动获取窗口小部件的消息的.
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;
}
这是我的查询功能现在的样子.请注意,没有正文可以放入Hibernate.initialize()
.
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?
推荐答案
尝试获取联接,如下所示:
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
这篇关于在@Query批注中指定查询时,如何使用Spring Data JPA初始化惰性关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文