What happens when two people edit a record at the same time? Unless something is done, the last person to save wins....the first edits are lost.
I'm seeking input on the following code I wrote to have some protection from this. All of my records have a "last_mod_date" field. When someone goes to a page, the keep track of the original last_mod_date value. When they save...the last_mod_date in the database is checked to see if it's still the same. If it's not, someone has changed the record...and the user is informed...and there are various resolutions that can be coded from that point.
Please read and comment on the following code and let me know if there is a better way to handle this situation.
Code:
/**
* safePersist(Metric) updates or saves specfied <code>Metric</code> through Hibernate.
* Checks to see that value of <code>last_mod_date</code> has not changed, and returns
* error if it has.
*
* @param Metric A <code>Metric</code> to be updated
* @param oldLastModDate the original lastModDate before any edits were done
*
*/
public String safePersist(Metric metric, java.util.Date oldLastModDate) throws InfrastructureException
{
Metric oldMetric; // initialize oldMetric
//
// Begin transaction so that two people can't save at the same time
//
Session session = HibernateUtil.getSession();
HibernateUtil.beginTransaction();
//
// Retrieve current record from database so that the last_mod_date
// can be compared
//
try {
oldMetric = (Metric) session.load(Metric.class, metric.getMetricId());
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
//
// Compare last_mod_dates...return exception if they are different...as that
// means that someone else has changed the record in the men time
//
if ( oldMetric.getLastModDate() != oldLastModDate) {
throw new InfrastructureException("Record was changed!");
}
//
// LastModDates are the same...so go ahead and save record
//
try {
HibernateUtil.getSession().saveOrUpdate(metric);
HibernateUtil.getSession().flush();
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
} catch (Exception e) {
throw new InfrastructureException(e);
}
return metric.getMetricId().toString();
}
Thanks in advance,
Lee