hibernateentity-relationshipcascadebidirectional-relation

Remove object with relationships - Hibernate


I'm having some problems with Hibernate relationships and Save-Update-Delete. Lets say I have the following:

 public class Subject{
      @Id
      private int ID;
      private String Name;
      //getters and setters
 }


 public class Grade{
      @Id
      private int ID;
      private String Name;
      //getters and setters
 }


 public class Course{
      @Id
      private int ID;
      @ManyToOne
      private Grade G;
      @ManyToOne
      private Subject S;
      //getters and setters
 }


 public class Teacher extends User{
      @ManyToMany
      List<Course> Courses = new ArrayList<Course>();
      //...
      //getters and setters
 }

And the thing is that, I can't simply delete a Subject, because it has relationships. I mean, when I delete a Subject, all the Courses which has that subject have to be deleted too. And, if a Course is deleted, the Subject that "belongs" to that Course should be existing though. And the same happens with the Grade and the Course.

My solution (temporarily) is: The method which deletes the Subject, calls the method which deletes all the Courses that have that subject BEFORE deleting the Subject itself.

But I'm sure this is not the correct way. I know that CascadeType should solve this problem, but I don't know which to use, neither when.

Now we are talking about Hibernate, should all relationships be bidirectional?


Solution

  • The Course entity is referenced by 3 entities and is not always the owning side. In this case, you should not use a cascade at all. The relationship would be in an inconsistent state after such a cascaded removal.

    Cascades are fine, when two entities have a one-to-many relationship, but for more entities and for many-to-many relationships (as well as for the many-side of a many-to-one relationship), you have to do it 'manually'.