I have a User object with a property of type bag which is a collection of objects representing IDs of items the user wishes to view. When the user attempts to update this collection, I get a primary key constraint violation, which I assume is due to Hibernate trying to re-insert pre-existing data. Here is the code for my update:
User u = uw.getUser();
u.getDesiredItems().clear(); // clear out old values
String[] items = (String[])PropertyUtils.getProperty(form, "itemId");
ArrayList itemList = new ArrayList();
for (int i = 0; items != null && i < items.length; i++) {
DesiredItem di = new DesiredItem();
di.setItemType("DESIRED_ITEM");
di.setItemValue(items[i]);
di.setUser(u);
itemLst.add(di);
}
u.setDesiredItems(itemList);
SessionFactory sf = (SessionFactory)JNDIUtils.lookup("java:/hibernate/HibernateFactory");
Session s = null;
Transaction transaction = null;
if (sf == null) {
System.out.println("Could not get a handle on the SessionFactory!!");
// throw an error
} else {
try {
s = sf.openSession();
transaction = s.beginTransaction();
s.saveOrUpdate(u);
transaction.commit();
} catch (HibernateException he) {
System.out.println("Could not update user: HibernateException: " + he.getMessage());
} finally {
try {
if (s != null) {
s.close();
}
} catch (HibernateException he2) {
System.out.println("Could not close session: HibernateException: " + he2.getMessage());
}
}
}
Hibernate should be deleting the collection first, then re-inserting the new data, right? I have default-cascade set to save-update for the User mapping. Any thoughts?
|