首页 > 解决方案 > Spring rest JPA 在创建 json 时需要忽略延迟初始化

问题描述

我正在使用弹簧休息,我对一件事感兴趣。当我分离对象并将其返回时,我收到下一个错误:Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: kz.training.springrest.entity.Publisher.books

我明白为什么。但我想知道是否有一些东西可以忽略这个异常并设置默认(空)值。

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@ToString
@Entity
public class Publisher {

    @Id
    @SequenceGenerator(name = "publisher_id_seq_gen", sequenceName = "publisher_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "publisher_id_seq_gen")
    private Long id;

    private String name;

    @OneToMany
    @JoinColumn(name = "publisher_id")
    private List<Book> books;

    public Publisher(Long id, String name){
        this.id = id;
        this.name = name;
    }
}


@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
public class Book {
    @Id
    @SequenceGenerator(name = "book_id_seq_gen", sequenceName = "book_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_id_seq_gen")
    private Long id;

    private String name;

}


@Service
public class BookService {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public Publisher selectPublisher(){
        Publisher publisher = entityManager.find(Publisher.class, new Long(1));
        entityManager.detach(publisher);
        return publisher;
    }
}

标签: javaspringjpa

解决方案


尝试将以下内容添加到您的 Book 和 Publisher 类中,以告诉您的 json 序列化程序忽略休眠字段:

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

参考:http ://www.greggbolinger.com/ignoring-hibernate-garbage-via-jsonignoreproperties/


推荐阅读