查询返回json时出现的错误,json解析使用jackson
1. 问题描述
实体如下:
Classify(分类):
@Entity
public classClassify {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer classifyId;
private String classifyName;
private Integer classifyParentId;
public Integer getClassifyId(){
return classifyId;
}
public void setClassifyId(IntegerclassifyId) {
this.classifyId = classifyId;
}
public StringgetClassifyName() {
return classifyName;
}
public void setClassifyName(StringclassifyName) {
this.classifyName = classifyName;
}
public IntegergetClassifyParentId() {
return classifyParentId;
}
public voidsetClassifyParentId(Integer classifyParentId) {
this.classifyParentId =classifyParentId;
}
}
Note(笔记):
@Entity
public classNote {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer noteId;
private String noteTime;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="classifyId")
private Classify classify;
private String keywords;
private String noteName;
private String noteContent;
private String noteSummary;
}
Note与Classify的关系是:多对一的关系
然后再Controller中获取指定noteId的Note
@RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
public Note queryNoteById(@PathVariable("id") Integer id){
log.info(id+"");
Notenote = null;
try {
note= noteService.queryNote(id);
note.getClassify().getClassifyId();
}catch(Exception e) {
log.error("查找id为" + id + "的笔记出现异常", e);
}
return note;
}
因为1那端是使用的时候才加载,这时候,访问…/query/2,会出现异常
com.fasterxml.jackson.databind.JsonMappingException:No serializer found for classorg.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no propertiesdiscovered to create BeanSerializer (to avoid exception, disableSerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain:com.pan.entity.dbentity.Note["classify"]->com.pan.entity.dbentity.Classify_$$_javassist_1["handler"])
com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
如果1那端不是懒加载,那么则不会出现异常
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="classifyId")
private Classify classify;
解决方案:
在关联实体类上标注@JsonIgnoreProperties注释
这里在Classify类上定义@JsonIgnoreProperties注释
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})
publicclassClassify {
。。。
}
上面两个值是必须的