Okay, so I have a situation where I have a many-to-many mapping table, however that mapping table also includes a date which effectively just records when the mapping was created.
I've used a three (/four) model solution for this, following MKYong's guide ( http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/ ). How I implemented it can be found at this unrelated Stackoverflow question ( http://stackoverflow.com/questions/22133787/hibernate-many-to-many-mapping-join-table-update-not-working/22143357#22143357 ). In there, you will see that I have a File, Directory, FileDirectory and FileDirectoryID classes to map the objects.
Now, the issue I get is when I go to update a directory back into the table. If the directory I'm updating had no previous FileDirectories, everything is fine. However, if when I selected the Directory object from the database, the object contained a many-to-many relationship, upon updating I get a NonUniqueObjectException (FileDirectory#******.***.***.FileDirectoryID@bfdc2cab). This happens despite the fact that I haven't actually modified or touched the FileDirectory/FileDirectoryID objects. However, the Set that they are stored in does also contain some new mappings that I need to pushed to the table.
If I run through the debugger, and follow FileDirectoryID@bfdc2cab , I know that it is the one generated when I performed my Select. However, at no point do I actually modify that object in any way, so I'm not understanding how it can be a "different object with the same identifier". It's the same object with the same identifier.
My get (select) code:
Code:
public DatabaseObject get(String columnName,
String columnValue) {
@SuppressWarnings("unused")
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
DatabaseObject object = null;
try {
trns = session.beginTransaction();
String queryString = "from " + objectType + " where " + columnName
+ " = " + columnValue;
Query query = session.createQuery(queryString);
object = (DatabaseObject) query.uniqueResult();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return object;
}
And my update code (also in the stackoverflow post, but I'll put it here for convenience):
Code:
public void updateObject(DatabaseObject object) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
session.update(object);
session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
Hopefully I've provided enough information for you guys to assist me with, I keep getting this feeling that it's just something small that I've missed out (well... I HOPE that's the case ;-) )
Thank you for your time,
Samuel