Hibernate: why do we use inverse=”true” in many to many

I was going through the hibernate tutorial, I couldn’t understand why they used inverse=”true” in the examples. The tutorial wasn’t clear enough.

Consider the case given in the example: Event and Person are two entities and there is a many to many mapping between  them. So when you add a event to a person using this code:

Event e=(Event)session.load(Event.class,eid);
Person p=(Person)session.load(Person.class,pid);
p.getEvents().add(e);
return p;//End of method

As in the above code, if you are making changes to only one end of the relationship (the Person end) then you don’t have to set inverse=”true” in the hbm file. But if you want the addtion of Events to a Person reflect on the Events entity (so that you can get persons attending an event using e.getPersons() )¬† with out causing hibernate to query the database when you do a event.getPersons(), you can do some thing like this

p.getEvents().add(e);//line a
e.getPersons().add(p);//line b
return p;//End of method

In this case, if you don’t set an inverse=”true”, you will get an error when hibernate tries to insert twice in the join table PERSON_EVENTS, once for line a and once for line b. Setting inverse=”true” on one side of the relationship tells hibernate to ignore changes to the relationship for this ‘many to many’ property. So if you set set inverse to true on one end of the relationship, you’ll see only one insert statement in hibernate log. If you set it on both ends, then hibernate won’t even insert a record in thte join table. If you still didn’t understand, please post your question and I’ll try to answer it.