今天在用spring boot想实现头通过url查询一个表单数据时,在service层用getOne(id),通过id获取书单。但结果一直报错,显示
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.zph.springbootdemo.domain.Book$ HibernateProxy$FBm7bZvb[“hibernateLazyInitializer”])
表示fasterxml.jackson将对象转换为json报错,序列化的时候实体有属性为null。
控制台也显示了book的内容,为什么会有null值呢,为什么会序列化错误呢?我不是很懂,希望得到大神的指点
解决方法:
根据小布吉岛的博客介绍,
getOne() 其实质只是返回实体对象的引用,如果没有实体类存在会抛出异常
findById() 的返回值是一个Optional,在Optional类中有个get()方法,返回的是当前对象值,可以有如下的写法,如果根据该id查找不到的话,是不能直接用get()方法的。
Optional<Book> book=bookRepository.findById(id);
if(book.isPresent())
return book.get();
else
return null;
所以将原先的getOne(id)改成findById(id).get()就可以了。