SpringMVC集成Hibernate返回json出现异常

查询返回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 {

   。。。

}

 

上面两个值是必须的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来了就走下去

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值