首页 > 解决方案 > 在相关实体中找不到类的序列化程序

问题描述

我正在研究从数据库中检索帖子的端点。但是我从杰克逊那里得到了一个不可序列化的错误:

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 都正确到位。

标签: javaspring-bootjackson

解决方案


推荐阅读