I'm using spring rest and I'm interested in one thing. When I detach my object and return it back I'm getting the next error: 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
I understand why. But I wanna know if there is something that can ignore this exception and set default(null) value for example.
@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;
}
}