Succinct Problem:
When I use an s.find("..") in onSave (Lifecycle) I get the following error: "SQL update or deletion failed (row not found)"
Using: hib2.1 with spring managed transactions through intercptors.
Is there a limitation to the use of find or the session whilst inside the onSave callback?
Verbose Problem:
I want to export a complex object graph to XML. And then import updates from XML.
I use a surrogate key (an int) in the database to identify unique objects, but I also use a uniqueId to identify my objects when in XML form.
eg:
Agent id:007 uid:Bond
in xml only the uid is exported:
<agent uid="Bond">xxxxxxx</agent>
Everything works fine but if I import an xml file wich includes "bond" when I save the agents to the db the unsaved-value causes all the agents to be created as new.
You may well ask why I don't update objects one-by-one. Well, I have a large object graph and cascade is working well up to now, I'd prefer to intercept the saves and then implement my own update.
So, I implemented this in onSave
Code:
public boolean onSave(Session s) throws CallbackException {
logger.debug("onSave... Agent. id="+getId() +" uid=" + getName());
//Check to see if uid is in the database
try {
logger.debug("Checking UID");
List agents = s.find("from com.xxx.Agent a where a.nam=?",
this.getName(), Hibernate.STRING);
return false;
//now check for Agents with this key
if (Agents.size()>0) {
logger.debug("uid match: "+this.getName()+" Swap objects, evict and update.");
Agent agent = (Agent) Agents.get(0);
//no we will swap this object for the Agent in
//memory and update (maintaining the id value)
//set id equal
this.setId(agent.getId());
s.evict(agent);
s.update(this);
//veto save
logger.debug("Vetoing save");
return true;
} else {
//no uid exists save continues as normal
logger.debug("No matching Uid: " + this.getName());
return super.onSave(s);
}
} catch (HibernateException e) { //
//throw on error
logger.debug(e);
throw new CallbackException(e);
}
}
But, I get terrible problems with "SQL update or deletion failed (row not found)" errors. I presume this is because of somehow accessing / changing data that is not yet written to the db. But as all of the object creation and modification is within the same session I thought this would all be handled by Hibernate. Any comments?
Thanks, Dan.