1

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;
    }
}

2 Answers 2

1

Try adding the following to your Book and Publisher classes to tell your json serializer to ignore the hibernate fields:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

You can also just add @JsonIgnore annotation to the property.
@ArloGuthrie those properties don't exist on the classes in the source code. They are created by hibernate at runtime when it proxies the Book and Publisher classes.
0

If you know which fields you want to ignore then you can use for eg: @JsonIgnoreProperties({"books"}).

But if you want a more generic solution you need to provide own converter alongwith ignoring "hibernateLazyInitializer" and "handler" like in the link Lucas provided.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.