在使用getOne()的时候以下报错
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.briup.bean.Role$HibernateProxyFALmmqvZ[“hibernateLazyInitializer”])
经实践有以下解决方法:
1.在报错的实体类上加,从上面的报错信息可知错误来自com.briup.bean.Role
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class Role implements Serializable {
}
2.在某些版本中可以
findById.get(id);代替getOne(id);
具体报错原理仅做记录,来自
-
https://www.bbsmax.com/A/MAzArvBRJ9/
-
https://segmentfault.com/a/1190000009150966
-
https://vladmihalcea.com/the-hibernate-enable_lazy_load_no_trans-anti-pattern/
getOne是懒加载,需要增加这个配置: spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true,但这种方式不太友好,建议不要使用。
每次初始化一个实体的关联就会创建一个临时的session来加载,每个临时的session都会获取一个临时的数据库连接,开启一个新的事物。这就导致对底层连接池压力很大,而且事物日志也会被每次flush.
设想一下:假如我们查询了一个分页list每次查出1000条,这个实体有三个lazy关联对象,那么,恭喜你,你至少需要创建3000个临时session+connection+transaction.