![](/img/trans.png)
[英]Spring Data, JPA @ManyToOne lazy initialization not working
[英]Spring rest JPA need to ignore lazy initialization when creating 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
我明白為什么。 但是我想知道是否有可以忽略此異常並設置例如default(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;
}
}
嘗試將以下內容添加到Book和Publisher類中,以告訴json序列化程序忽略休眠字段:
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
參考: http : //www.greggbolinger.com/ignoring-hibernate-garbage-via-jsonignoreproperties/
如果您知道要忽略的字段,則可以使用例如: @JsonIgnoreProperties({"books"})
。
但是,如果您需要更通用的解決方案,則需要提供自己的轉換器,並忽略Lucas提供的鏈接中的“ hibernateLazyInitializer”和“ handler”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.