Just after I sent my previous post I found a way to accomplish what I was doing, by using the function listed below.
I have another question though, am trying to understand this. Users can have many favourite events and events could be a part of many users as their favourite events , therefore I define this:
Code:
<set name="favouriteEvents" table="favourite_events">
<key column="user_uid"/>
<many-to-many
column="event_uid"
class="med.allegro.events.Event"/>
</set>
Now, how do I tell hibernate to delete all associations from the favourite_events table when I delete a favourite event from the favouriteEvents Set in the User ?
i.e. If I were to do this:
User user1 = (User) users.get(0);
instance.deleteUser(user1);
QUESTION 1: I want the user1 and the associated records from the favourite_events table deleted. When I delete the user1. Is there a way to get this accomplished?
QUESTION 2: Have I written the removeFavouriteEvents function optimally or is there an easier way to do this?
Thanks.
Listing:
Code:
public void removeFavouriteEvents(User user, Event event)
{
try
{
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User u1 = getUser(user.getId());
Set favouriteEvents = u1.getFavouriteEvents();
if(favouriteEvents != null && favouriteEvents.isEmpty() == false)
{
Event evt = null;
Iterator it = favouriteEvents.iterator();
boolean f = false;
while(it.hasNext() && f == false)
{
evt = (Event)it.next();
if( evt.getId().longValue() == event.getId().longValue())
{
f = true;
}
}
if(f == true)
{
favouriteEvents.remove(evt);
}
}
u1.setFavouriteEvents(favouriteEvents);
session.update(u1);
session.flush();
tx.commit();
session.close();
}
catch (HibernateException e)
{
e.printStackTrace();
}
}
Code:
private void deleteUser(User user)
{
try
{
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.delete(user);
tx.commit();
session.close();
}
catch(HibernateException ex)
{
ex.printStackTrace();
}
}