java - 在相关实体中找不到类的序列化程序
问题描述
我正在研究从数据库中检索帖子的端点。但是我从杰克逊那里得到了一个不可序列化的错误:
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.quantumx.NutriRecord.domain.Post["usuario"]->com.quantumx.NutriRecord.domain.Usuario$HibernateProxy$RjPKYnnj["hibernateLazyInitializer"])
与 Post 和 User (Usuario) 类的绑定有关。
这是 Post 实体类:
@Entity
@Table(name = "post")
public class Post extends RepresentationModel<Post> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long postid;
@Column
private String contenido;
@Column
private Boolean liked;
@Column
private ZonedDateTime fechacreacion;
@Column
private ZonedDateTime fechaactualizacion;
// @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="usuarioid", referencedColumnName = "usuarioid")
private Usuario usuario;
// Setters and Getters
这是控制器动作:
@GetMapping("/{id}")
public ResponseEntity<?> getPost(@PathVariable("id") Long id, HttpServletRequest request, Authentication auth) {
try {
Post post = postService.getPostById(id);
HashMap<Long, Boolean> usuarios = postService.findAllowedUsers(post.getUsuario(), auth);
if ( usuarios.containsKey(post.getUsuario().getUsuarioid())) {
post.add(linkTo(methodOn(ConversacionController.class).getPost(id, request, auth)).withSelfRel());
List<Comment> comments = commentService.findAllByPost(post);
if (!comments.isEmpty()) {
post.add(linkTo(methodOn(ConversacionController.class).getAllComments(id,request)).withRel("allComments"));
for (Comment comment : comments) {
Long id_comment = comment.getCommentid();
post.add(linkTo(methodOn(ConversacionController.class).getComment(id, id_comment, request)).withRel("comment"));
}
}
return new ResponseEntity<Object>(post, HttpStatus.OK);
}
else {
return new ResponseEntity<MessageResponse>(new MessageResponse("Access denied"), HttpStatus.FORBIDDEN);
}
}
catch (Exception e) {
return new ResponseEntity<MessageResponse>(new MessageResponse(e.getMessage()), HttpStatus.NOT_FOUND);
}
}
最后,这是端点用于检索 Post bean 的服务实现:
@Override
public Post getPostById(Long id) throws Exception {
//Return Post if exits, else, return a not found exception
return postRepository.findById(id).orElseThrow(() -> new Exception("Post con id " + id + " no encontrado!"));
}
正如我们所见,我可以通过在相关属性中添加注释 @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})或将属性获取类型更改为EAGER来解决此问题。但是我想了解为什么会出现这个错误,因为已经尝试在控制器方法中调用 post.getUsuario()并且我所有的 getter/setter 都正确到位。
解决方案
推荐阅读
- android - 如何防止手机进入空闲模式
- c++ - 如何有效地找到数字内的数字加起来为特定数字的范围内的数字位数
- c++ - 我可以在 IOCP WSARecv 函数中使用 std::string 吗?
- docker - 如何使来自 docker 容器内部的请求看起来来自我的本地计算机?
- java - 无论线程如何,一个对象是否总能看到其最新的内部状态?
- python - Cython UserWarning:未知扩展选项:'cython_compile_time_env'
- ansible - 尽管条件为假,Ansible 仍继续尝试插入变量
- sentiment-analysis - 我需要过去 3-4 个月与任何公司/商品相关的 twitter 数据集来预测股价
- sql - 在批处理文件中将 SQL 文件与命令 `copy` 结合会引入不正确的语法,因为它确实添加了不可见字符 `U+FEFF`
- javascript - 在日期选择器的事件发射器中发射日期对象