如何在没有递归的情况下实现双向实体引用,示例如下

How to implement two way entity reference without recursion, example below

我有 2 个引用的实体 Author 和 Book,它们之间有 many2one=>one2many 的引用,我在实现时遇到问题?当进入 /authors 时,我得到所有作者的书,但每本书中都有他的作者(有自己的书),反之亦然

有一点有问题,我需要得到 /authors - 所有没有他的书的作者
/author/{id} 和他所有的书(里面的书不需要作者) /books 所有书内有作者的书(但书内不需要作者) /book/{id} 有作者的书(里面没有他的书)

@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; ....

@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; ....

我会从 Author 中删除 private List<Book> books;,而是创建一个服务:

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

就像人类作者不会一直随身携带所有已出版的书籍一样,Java 同行也不应该。