【问题标题】:How to implement two way entity reference without recursion, example below如何在不递归的情况下实现双向实体引用,示例如下
【发布时间】:2020-01-14 07:14:29
【问题描述】:

我有 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; ....

【问题讨论】:

  • 看起来你需要这个来进行 json 序列化(也许是一个休息端点?),你检查过this 帖子了吗?
  • 是的,但下面的回答是我最好的方法
  • 我的建议是不要在一个类中混合实体和 dto。使用显式映射,您可以获得任何您想要的东西而不会产生副作用。更多详情请参阅我的文章(俄语)dou.ua/lenta/articles/how-to-use-hibernate

标签: java hibernate jpa reference entity


【解决方案1】:

我会从 Author 中删除 private List&lt;Book&gt; books; 并创建一个服务:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多