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;
...
}
另外,还有过滤器法,这个还没有搞懂,暂时搁置。