kravicha wrote:
Hi,
You need not do a saveOrUpdate explicitly to insert your collection/child object.
You use cascade=save-update in your .hbm file for the collection entity.By doing this you need not explicitly call saveOrUpdate.You retrieve your Parent/Main object and in the same session just set this Collection Object and close the transaction and session.Your collection object will be persisted.
inverse=true just indicates Hibernate that you need to avoid multiple insert on the rows which might result in error.It indicates hibernate that its the collection is the mirror image of the other.So any insert/update on one side will ignore the insert/update on other.
Read This article
http://suneelgv.wordpress.com/2008/11/2 ... y-to-many/kartik
we can call saveOrUpdate on both parent and child. But with cascade options it is unnecessary. With cascade,saving the parent would save the collection as well. Even if you call saveOrUpdate(child) immediately after saveOrUpdate(parent), hibernate is not going to queue any sql statements for the second call.
For example,
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Child child= new Child();
child.setName("child1");// child has a hibernate generated surrogate key
List<Child > children= new ArrayList<Child >();
children.add(child);
Parent parent = new Parent (); //parent has a hibernate generated surrogate key as well
parent.setName("parent");
parent.setChildren(children);
child.setParent(parent );
session.saveOrUpdate(parent );
session.saveOrUpdate(theEvent);// This call is unnecessary with above cascade settings. Hibernate will not generate any sql for this
// but won't produce error because hibernate is going to ignore this.
session.getTransaction().commit();
So with cascade options you are simply saving the lines of code.
Inverse has a totally different purpose.
But inverse="true", you tell the foreign key should be inserted/updated by child.