【发布时间】: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