hinbernate懒加载异常org.hibernate.LazyInitializationException: could not initialize proxy - no Session

        DataGridJSONModel json = new DataGridJSONModel();       
        PageHolder<IP> holder = ipdao.findPage(page, rows);
        List<IP> list = holder.getList();
        json.setRows(list);
        json.setTotal(holder.getTotal());       
        return json;

在将返回对象json转换为JSON语句时报错

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: could not initialize proxy - no Session (through reference chain: com.liyunet.common.json.DataGridJSONModel["rows"]->java.util.ArrayList[0]->com.liyunet.domain.IP["attachments"]->com.liyunet.domain.IPAttachments_$$_jvst7f7_1c["id"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.liyunet.common.json.DataGridJSONModel["rows"]->java.util.ArrayList[0]->com.liyunet.domain.IP["attachments"]->com.liyunet.domain.IPAttachments_$$_jvst7f7_1c["id"])
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:276)
    org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
    ... ...

可以看出类IP中attachments属性初始化代理失败,原因是没有session(session已关闭)。下面是在实体类IP中的定义代码

    @OneToOne(fetch = FetchType.LAZY)//懒加载
    @JoinColumn(name = "attachements_id")
    private IPAttachments attachments;

所以,实际上返回的对象json中rows中对象IP的属性attachments是个代理,所以要初始化。
有三种方法解决此问题:

1. 遍历传递给rows的list,使用Hinbernate.initialize(attachments);初始化attachments字段。
list.forEach(ip -> {
    IPAttachments attachments = ip.getAttachments();
    Hibernate.initialize(attachments);
});
2. 使用hql语句立即加载attachments字段。

修改查询list的hql语句为:

String hql = "from IP ip inner join fetch ip.attachments order by ip.points desc";
3.使用VO,即将对象IP中需要的几个字段查询出来保存到一个实体类中,POJO,这样session关闭之前就会加载,便不会懒加载异常。
class VO{
    private String id;
    ...
}

另外,还有过滤器法,这个还没有搞懂,暂时搁置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值