我有一个课程复习一对多关系。在“课程”表中,有id和title列。在“评论”表中,有id,注释和带有“ course_id”的Course_id,FK指向课程ID。我想知道这样的情况:课程一经删除,相关的评论应自动删除。我有以下代码:
@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();
}
}
}
我发现我可以成功删除该课程,但未删除这三个评论。在搜索与stackoverflow相关的帖子之后,我还尝试使用orphanRemoval = true,但仍然无法正常工作。
答案 0 :(得分:2)
由于您从未初始化关联的拥有部分:sh "curl -0 https://url.com/path1/somefile.1
curl -0 https://url.com/path2/somefile.2
curl -0 https://url.com/path3/somefile.3
aws s3 copy ./somefile.1 s3:bucket
aws s3 copy ./somefile.2 s3:bucket
aws s3 copy ./somefile.3 s3:bucket"
,因此您的评论永远不会真正属于该表述。将您的Review.course
方法更改为
addReview()