This is a specific version of this question.
I want to check if I am inserting a duplicate row. Should I check it programmatically in my application layer:
if (exists(obj))
{
throw new DuplicateObjectException();
}
HibernateSessionFactory.getSession().save(obj);
or should I catch the exception thrown by the database layer and triggered when I violate the contraint?
try
{
HibernateSessionFactory.getSession().save(obj);
}
catch(ConstraintViolationException e)
{
throw new DuplicateObjectException();
}
EDIT: In other words: though the constraint is there to remain (it's good database design anyway, and I can't be sure my app will be the only one accessing the table) shall I rely on the constraint and handle the exception its violation will raise, or I'd better check anyway?
EDIT2: Of course I do check+insert within a transaction, locking the table to ensure no other process is writing another record in the meantime