failed to lazily initialize a collection of role: could not initialize proxy - no Session

在hibernate映射关联时

  有类似下面的注解 

@OneToMany(mappedBy = "appEntity",fetch = FetchType.LAZY) 其中 fetch = FetchType.LAZY表示懒加载。

private Set<ProductEntity> productEntities;

 

结果在运行时遇到下面的错误:

     failed to lazily initialize a collection of role: could not initialize proxy - no Session。

  运行代码如下:

 public List<AppEntity> getAppListWithPageKeyword(int page,int step, String keyword){

    Session session = HBSession.getSession();
String hql = "from com.wawagame.backend.trade.hbentity.AppEntity as app where app.appName like :appName";
Query query = session.createQuery(hql);
query.setString("appName","%" + keyword + "%");
query.setFirstResult((page - 1) * step);
query.setMaxResults(step);
List<AppEntity> list = query.list()
session.close();
return list;
}
pulic static void mian(String args){
  List<AppEntity> appEntity = getAppListWithPageKeyWord(1,10,"");
  System.out.println(
list.get(0).getProductEntities());
}
原因是在在懒加载是session关闭和数据库的链接关闭了。
解决办法:
  1、fetch = FetchType.LAZY 在成 fetch = FetchType.
EAGER 一次讲所有数据查询出来
  2、在session关闭之前获取如

List<AppEntity> list = query.list()
System.out.println(list.get(0).getProductEntities());
session.close()
 



 

 

 

      

posted @ 2017-05-27 16:46  三里路异乡客  阅读(1398)  评论(0编辑  收藏  举报