0

I have 2 referenced entity Author and Book and have reference many2one=>one2many between it, i have a problem with realization? when in go to /authors i get all authors with his books inside but inside each book have his author (with all own books) and vice versa

Problem in one point, i need get /authors - all authors without his books
/author/{id} with all his books (inside books dont need author) /books all books with authors inside book (but inside book dont need author) /book/{id} book with author (without his books inside)

@Entity(name = "Author")
@Table(name = "authors")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "author", cascade = CascadeType.ALL)
    private List<Book> books; ....

and

@Entity
@Table(name = "books")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Book{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "price")
    private double price;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author; ....

  • It looks like you need this for json serialization (maybe for a rest endpoint?), did you check [this](https://stackoverflow.com/questions/25906985/jackson-do-not-serialize-lazy-objects) post already? – PaulD Sep 12 '19 at 12:25
  • yeap but answer below are my best way – Maxym Rudenko Sep 12 '19 at 13:23
  • My suggestion is not mixing entity and dto in a single class. Using explicit mapping you may get whatever you want without side effects. See my article (in Russian) for more details https://dou.ua/lenta/articles/how-to-use-hibernate – Andriy Slobodyanyk Sep 12 '19 at 14:36

1 Answers1

0

I would remove the private List<Book> books; from Author and instead create a service:

public class BookService {
    public List<Book> getBooks(int authorId) {
        // look up the books by author_id
    }
}

Just like a human author doesn't carry all his published books around with him at all times, the Java counterpart shouldn't either.

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60