我用的是弹簧支架,我只对一件事感兴趣。当我分离我的对象并返回它时,我得到了下一个错误: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
我明白为什么。但是我想知道是否有一些东西可以忽略这个异常,并设置默认值(Null)。
@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;
}
}
发布于 2018-06-04 21:19:16
尝试将以下代码添加到Book和Publisher类中,以告知json序列化程序忽略hibernate字段:
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
参考:http://www.greggbolinger.com/ignoring-hibernate-garbage-via-jsonignoreproperties/
发布于 2018-06-05 03:36:02
如果您知道要忽略哪些字段,则可以使用for,例如:@JsonIgnoreProperties({"books"})
。
但是如果你想要一个更通用的解决方案,你需要提供自己的转换器,同时忽略"hibernateLazyInitializer“和"handler”,就像卢卡斯提供的链接一样。
https://stackoverflow.com/questions/50681157
复制相似问题