gpt4 book ai didi

java - Hibernate一对多关系: can't remove children once parent is removed

转载 作者:行者123 更新时间:2023-11-29 06:40:47 29 4
gpt4 key购买 nike

我有类(class)评论一对多关系。在类(class)表中有 id 和 title 列。在 Review 表中,有 id、comment 和 course_id,其中“course_id”作为指向类(class) id 的 FK。我想实现这样的场景:一旦类(class)被删除,相关的评论应该自动删除。我有以下代码:

@Entity
@Table(name = "course")
public class Course {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

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

@OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Review> reviews;

public void addReview(Review review){
if(reviews==null) reviews = new ArrayList<>();
reviews.add(review);
}

//other codes below omitted
}



@Entity
@Table(name = "review")
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

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

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "course_id")
private Course course;

//other codes omitted
}

客户端代码:

public class Client_OneToMany_bidirectional {
public static void main(String[] args) {

SessionFactory sf = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.addAnnotatedClass(Review.class)
.buildSessionFactory();

Session session = sf.getCurrentSession();

try{
//add course and review
Course course = new Course("How to learn Java");

course.addReview(new Review("Good course!"));
course.addReview(new Review("I love it!"));
course.addReview(new Review("Need some more!"));

session.beginTransaction();
System.out.println(course);
System.out.println(course.getReviews());
session.save(course);
session.getTransaction().commit();

//start to delete the course
session = sf.getCurrentSession();
session.beginTransaction();
Course crs = session.get(Course.class, 12);
if(crs != null ){
session.delete(crs);
}
session.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
}finally {
session.close();
sf.close();
}
}
}

我发现我可以成功删除类(class),但三个评论没有被删除。在搜索 stackoverflow 相关帖子后我也尝试使用 orphanRemoval=true 但它仍然不起作用。

最佳答案

您的评论从未真正属于该类(class),因为您从未初始化该协会的所有权部分:Review.course。将您的 addReview() 方法更改为

@OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Review> reviews = new ArrayList<>();

public void addReview(Review review){
review.setCourse(this);
reviews.add(review);
}

关于java - Hibernate一对多关系: can't remove children once parent is removed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696883/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com