Hibernate SpringBoot父子关系
我有以下Springboot代码: Comment.javaHibernate SpringBoot父子关系,hibernate,spring-boot,Hibernate,Spring Boot,我有以下Springboot代码: Comment.java @Entity @Getter @Setter @NoArgsConstructor @RequiredArgsConstructor public class Comment extends Auditable { @Id @GeneratedValue private Long id; @NonNull private String comment; @ManyToOne(fe
@Entity
@Getter @Setter @NoArgsConstructor @RequiredArgsConstructor
public class Comment extends Auditable {
@Id
@GeneratedValue
private Long id;
@NonNull
private String comment;
@ManyToOne(fetch = FetchType.LAZY)
private Link link;
}
Link.java
@Entity
@Getter @Setter @NoArgsConstructor @RequiredArgsConstructor
public class Link extends Auditable {
@Id
@GeneratedValue
private Long id;
@NonNull
private String title;
@NonNull
private String url;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "link")
private List<Comment> comments = new ArrayList<>();
public void addComment(Comment c) {
comments.add(c);
}
}
我正在尝试将评论链接到链接,并将两者保存在一起。但是,这是输出:
[
{
createdBy: null,
createdDate: "2/28/19, 11:48 PM",
lastModifiedBy: null,
lastModifiedDate: "2/28/19, 11:48 PM",
id: 2,
comment: "Hello!",
link: null
}
]
关于如何让链接实际显示在链接列表中的任何建议?在双向关系中,必须设置关系的两侧
Link link = new Link("Getting started", "url");
Comment comment = new Comment("Hello!");
comment.setLink(link); // missing in your code
link.addComment(comment);
linkRepository.save(link);
选中“双向多对一关联”“>您需要添加
c.setLink(此链接)
在addComment
方法中。您好,谢谢,我的印象是CascadeType.ALL也适用于相关实体(即:注释)?从这里开始:我明白了,我会想,因为我在注释中有mappedBy参数,它会自动完成,但似乎不是。有没有办法配置它,以便在我向链接添加注释时,它也会自动向注释添加链接?我想我可以在addComment方法中做一些类似comment.setLink(this)的事情,但我希望一些自动配置可以让SpringBoot获取它automatically@MrD我有确切的想法,但不确定为什么它不在那里。一定是在某些情况下,它打破了覆盖在上面的持久性逻辑?看起来很琐碎,但我们需要明确并手动执行。。。我们有50个表连接到一个单亲表,在一个5步深的层次结构中。你能想象恐怖吗?我已经创建了一个完整的自动化通用实体结构,以便按照您的建议处理它=PMakes sense谢谢,现在我刚刚添加了comment.setLink(这个);在addComment方法中,它似乎是有效的。谢谢你的帮助!
Link link = new Link("Getting started", "url");
Comment comment = new Comment("Hello!");
comment.setLink(link); // missing in your code
link.addComment(comment);
linkRepository.save(link);