今天用springMVC
@ResponseBody 返回一个有懒加载对象的时候出现了错误,
网上查了下可以在pojo中生成一个构造函数,不包括我们的懒加载对象
public News(int id, String newContent, Date addDate, Date updateDate, String addUser, String updateUser, int isFlag, String newsStaticUrl, int is_enable, String newsTitle, String newsDesc, int orderNumber) {
this.id = id;
this.newContent = newContent;
this.addDate = addDate;
this.updateDate = updateDate;
this.addUser = addUser;
this.updateUser = updateUser;
this.isFlag = isFlag;
this.newsStaticUrl = newsStaticUrl;
this.is_enable = is_enable;
this.newsTitle = newsTitle;
this.newsDesc = newsDesc;
this.orderNumber = orderNumber;
}
然后hql查询时用:
Query query = entityManager.createQuery("select new News(s.id,s.newContent,s.addDate,s.updateDate,s.addUser,s.updateUser,s.isFlag,s.newsStaticUrl," +
"s.is_enable,s.newsTitle,s.newsDesc,s.orderNumber) from"+sql.toString());
因为懒加载这个对象属性只是一个代理对象,如果json直接当作一个存在的属性去序列化就会出现错误,所以就只能这样了,当然还有其他办法吧
或者在class上加上
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class ProductPrice {
}
springMVC 返回json报500错误的话可以
ObjectMapper mapper=new ObjectMapper();
try {
String jsonString=mapper.writeValueAsString(object);
System.out.print(jsonString);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在后台序列化一下,看看报的错误是什么,然后再去网上查查错误的解决方法