java - 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;
}
}
解决方案
尝试将以下内容添加到您的 Book 和 Publisher 类中,以告诉您的 json 序列化程序忽略休眠字段:
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
参考:http ://www.greggbolinger.com/ignoring-hibernate-garbage-via-jsonignoreproperties/
推荐阅读
- mongodb - Cubejs:错误:19488:错误:1408F10B:SSL 例程:ssl3_get_record:错误的版本号:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:
- mysql - mySQL:查询/合并重复项+ Concat
- c - 计算C中嵌套目录中文件的块大小
- algorithm - 采样 xy 平面中的螺旋
- java - Java 流中奇怪的 lambda 行为
- c++ - Address Sanitizier 调用 OOM-killer
- javascript - 未找到模块:错误:在 Vue 和 Laravel 中
- javascript - 用于 NodeJS 的轻量级 AWS S3 客户端
- azure - 使用scala检查parquet文件是否存在
- angular - 构建门户网站应用架构