Hi all,
I've been struggling here for a bit. I'm trying to use the saveOrUpdate to save/update an object where I don't want to use the primary key (id which is generated) but rather a different column (name for example). Avoiding a lot of background discussion, the situation I'm in I have no control over. I'm given a file of serialized objects of many differeny types generated at a remote site and I need to persist them locally. Obviously, the generated IDs of the objects are not going to match - they are from two SQL servers that have no communication to each other. So saveOrUpdate will always just create new rows. What I want to do is update if the 'name' is the same or save (create) if the name is unique.
I tried changing the @Id annotation to the name colum on my dev machine and saveOrUpdate worked perfectly. Sadly, I don't have control over that in production.
I've seen some good articles on merge, where I set the new object's ID to the local ID and then merge, but it poses some problems as I would have to know the object type. I do - but I'd love to keep this as generic as possible. There is a lof of code to change.
After all that rambling, here is my question -
Is there an annotation I can put on the entity for saveOrUpdate to use in place of the ID? I can't use a hibernate XML file - everything is in code.
Code:
newObject = getObjectFromFile(...);
oldObject = getObjectFromLocalDatabase(...);
// I'd really like to not have to do this since I have to know the object types
newObject.setId(oldObject.getId());
HibernateDAOUtil.getSession().beginTransaction();
HibernateDAOUtil.getSession().saveOrUpdate(merge(newObject));
HibernateDAOUtil.getSession().getTransaction().commit();
public <T> Object merge(T entity) throws Exception {
return HibernateDAOUtil.getSession().merge(entity);
}
public <T> void saveOrUpdate(T entity) throws Exception {
Session session = HibernateDAOUtil.getSession();
session.saveOrUpdate(entity);
}
References:
Cameron McKenzie's 'Hibernate Made Easy book
http://stackoverflow.com/questions/2857 ... veorupdate