title: Logic: Database or Application/2 (constraints check)
body: <p>This is a specific version of <a href="https://stackoverflow.com/questions/119540/business-logic-database-or-application-layer">this question</a>.<br/>
  I want to check if I am inserting a duplicate row. Should I check it programmatically in my application layer:</p>
  
  <pre><code>if (exists(obj))
  {
      throw new DuplicateObjectException();
  }
  HibernateSessionFactory.getSession().save(obj);
  </code></pre>
  
  <p>or should I catch the exception thrown by the database layer and triggered when I violate the contraint?</p>
  
  <pre><code>try
  {
      HibernateSessionFactory.getSession().save(obj);
  }
  catch(ConstraintViolationException e)
  {
      throw new DuplicateObjectException();
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> 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?</p>
  
  <p><strong>EDIT2:</strong> Of course I do check+insert within a transaction, locking the table to ensure no other process is writing another record in the meantime</p>