Felix
Felix

Reputation: 1263

delete detail from database using spring-data-jpa

Now I am using spring-data-jpa & hibernate. I want to delete a courseDetail from the course, But after I run my code below the courseDetail is still in the database.

Who can tell me how this happened?

thanks in advance.

@Transactional(readOnly = false)
public void deleteCourseDetail(Long id, Long courseId) {
    Course course = courseDao.findOne(courseId);
    CourseDetail courseDetail = courseDetailDao.findOne(id);
    System.out.println(course.getCourseDetails().size());
    course.getCourseDetails().remove(courseDetail);
    System.out.println("after: " + course.getCourseDetails().size());
    courseDao.save(course);
}

@OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
public List<CourseDetail> getCourseDetails() {
    return courseDetails;
}

Now it works after I add courseDetailDao.delete(id); behind save method. but WHY?

Upvotes: 0

Views: 1244

Answers (1)

Adrian Shum
Adrian Shum

Reputation: 40066

You should have "delete orphan" as the cascade type.

If not, deleting an entry in courseDetails simply means removing the relationship between Course and CourseDetail. It does not mean removing a courseDetail from DB

Upvotes: 1

Related Questions