user911651
user911651

Reputation:

Saving/updating Hibernate Entities with many-to-many relationships

I am currently trying to solve a problem, that I have using Hibernate 4 in a Java Swing application while having several many-to-many relationships between entities.

For example, the Project entity has a relationship with Person. Person and Project have a many to many relationship. A Project can be in many Categories, so there is a many-to-many relationship as well.

Person *-----* Project *-----* Category

When I have a swing form where I can edit all this information about a Person, a Project and a Category and it comes to saving the Person when the user hits the "save" button, what would be a possible solution to save/update Person?

void savePerson(Person p){
   Session sess = factory.openSession();
   Transaction tx = null;
   try {
       tx = sess.beginTransaction();

       // steps to be done

       tx.commit();
   }
   catch (RuntimeException e) {
       if (tx != null) tx.rollback();
   }
   finally {
       sess.close();
   }
}

Because there is also a collection of Projects inside Person and a collection of Categoy inside Project that might have been changed, do I have to do a recursive type of saving (first save/update all the sub-entities that the collections contain and then save/update the Person entity) or do I have to only save the Person entity and Hibernate applies the save/update mechanism to the whole entity-tree with Person as the root? Any best practices?

Upvotes: 4

Views: 3877

Answers (1)

halfdan
halfdan

Reputation: 34204

Have a look at CascadeType. You can set the behaviour for save/update operations directly by using the CascadeType in the relationship annotation:

@OneToMany(cascade = CascadeType.ALL)

Upvotes: 2

Related Questions