title: Hibernate: Check foreign key constraint violation before delete?
body: <p>The system I'm currently working on has a policy in which objects that have no relationships can be freely deleted, while those that do must be logically deleted. This is meant to prevent historical information from being deleted.</p>
  
  <p>So basically, what I was trying to do was determine whether an object's key is currently present in another table. If it isn't I would simply call delete(), otherwise I would set a property that indicates a logical delete, and call update().</p>
  
  <p>I'm using Spring transaction management, so I'm trying to mess with the session itself as least as possible. My initial approach seemed to work at first, but you'll see that it has a major flaw:</p>
  
  <pre><code>@Transactional
  public void deleteObject(SomeEntity object)
  {       
      //try to delete
      this.someEntityDAO.delete(object);
  
      try //force foreign key constraint check
      {
          this.someEntityDAO.flush();
      }
      catch (ConstraintViolationException e)
      {
          //reload object
          object= this.someEntityDAO.loadById(object.getId());
  
          //save as inactive instead of deleting
          object.setActive(false);
          this.someEntityDAO.update(object);
      }
  }
  </code></pre>
  
  <p>Since Hibernate exceptions are fatal, this is completely unreliable (even though it works). I was wondering if there is a way to do a sort of "peek" operation in which I could test if the delete will fail due to a constraint, without actually performing the operation (and thus invalidating the session). The only thing I can think of is to manually check each related table to see if the id is present, but this would be very tedious and error-prone in tables with many relationships. I want to leverage the constraints that are already in place in the database, if possible.</p>