That depends on what version of hibernate you're using. If your version has session.merge, you could use that: don't record the return value, and query by example on the initial parameter (x in above example) after the transaction commits. Querying by example on a fully-populated object with not id should return the persistent version of that object. Something like:
Code:
try
{
sess.beginTransaction();
y = session.merge(x);
sess.commitTransaction();
}
catch (HibernateException e)
{
sess.rollbackTransaction();
y = x;
}
x = y;
// Now both y and x are correct: if the transaction was
// successful, they're both the persistent version;
// if the transaction was rolled back, they're both the
// original version with no id.
It must be said that by and large, this problem doesn't come up often because objects involved in a rolled back transaction are usually discarded. At best, they're used to re-populate a form, then discarded. So having a generated id in them isn't a factor. Can you change to working that way?