title: Dynamic suppression of EntityNotFoundException in Hibernate
body: <p>The following method executes a simple query via <a href="http://hibernate.org/" rel="nofollow noreferrer">Hibernate</a> to retrieve some custom <code>Entity</code> records from a database, given their unique IDs:</p>
  
  <pre><code>  public List&lt;Entity&gt; getEntity(Collection&lt;Long&gt; ids) {
      Session session = null;
      String sqlQuery =
        "SELECT entities.* FROM entities WHERE entities.id IN :ids";
      try {
        session = createSession();
        NativeQuery&lt;Entity&gt; query = session.createNativeQuery(sqlQuery)
          .addEntity(Entity.class)
            .setParameter("ids", ids);
        List&lt;Entity&gt; entities = query.list();
        return entities;
      } catch (Exception e) {
        log.error(e);
        return null;
      } finally {
        if (session != null) {
          session.close();
        }
      }
    }
  </code></pre>
  
  <p>The code above seems to work as expected if the list of IDs supplied can be found in the database, but if any of the given IDs does not correspond to an existing record, the following exception is thrown:</p>
  
  <pre><code>javax.persistence.EntityNotFoundException: No row with the given identifier exists
  </code></pre>
  
  <p>To suppress this exception statically (i.e., at compile time), the following annotation can be used in the <code>Entity</code> class:</p>
  
  <pre><code>@NotFound(action=NotFoundAction.IGNORE)
  </code></pre>
  
  <p>However, this approach is not an option if, for instance, the <code>Entity</code> class definition cannot be modified by client code.</p>
  
  <p>Is there any way to suppress the exception dynamically (i.e., at runtime), e.g. on a per-query basis?</p>