【hibernate 报错】No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 【get和load的区别】

时间:2023-01-03 13:34:38

报错:

 HTTP Status 500 - Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered
to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.agen.entity.Product_$$_jvst2a_3["handler"]);
nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no
properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.agen.entity.Product_$$_jvst2a_3["handler"])

出现这个问题,是因为:

 @ResponseBody
@RequestMapping("/Updateproduct")
@Transactional
public Product updateProduct2(Product product){
Product product1 = productService.load(product.getProductId());
if(product1 != null){
product1.setProductName(product.getProductName());
product1.setProductCre(product.getProductCre());
} return product1;
}

这个方法中使用的load()获取到数据库中的这一条数据。

使用load()时,进入BUG模式可以看到,虽然获取到这条数据,但是你要看,却发现展示出来的这个对象的字段都是null。

【hibernate  报错】No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 【get和load的区别】

但是其中是有值的!!

【hibernate  报错】No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 【get和load的区别】

这样返回给前台,前台接收不到值,会跑出异常:

【hibernate  报错】No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 【get和load的区别】

修改:

于是我们应该将load()方法修改为get()方法

 /**
* 进行产品修改操作
* @return
*/
@ResponseBody
@RequestMapping("/Updateproduct")
@Transactional
public Product updateProduct2(Product product){
Product product1 = productService.get(product.getProductId());
if(product1 != null){
product1.setProductName(product.getProductName());
product1.setProductCre(product.getProductCre());
} return product1;
}

这样就能解决这个问题!!