title: How to secure Hibernate QBE query
body: <p>By the moment, I know four kinds of doing transactions with hibernate:</p>
  
  <ol>
  <li>Using objects</li>
  <li>Using HQL</li>
  <li>Using DB-specific SQL</li>
  <li>Using criteria (QBE)</li>
  </ol>
  
  <p>Well, regarding how strong are they against injections, I think these are (correct me if I'm wrong):</p>
  
  <ol>
  <li>Secure, because the internal SQL call is parameterized.</li>
  <li>Secure if the query is parameterized, insecure otherwise.</li>
  <li>Same as #2 but not as portable.</li>
  <li>Insecure?</li>
  </ol>
  
  <p>My question is about #4, Query by Example, because i've found it is also vulnerable. Example:</p>
  
  <pre><code>    Account a = new Account(); //POJO class       
      a.setId("1' OR '1'='1");
  
      //s is a org.hibernate.Session instance
      Criteria crit = s.createCriteria(Account.class);
      crit.add(Example.create(a));
      List results = crit.list();  //table dump!
  </code></pre>
  
  <p>That snippet selects the whole accounts table. Is there any way to prevent injection? How?</p>
  
  <p>NOTE: I'm using Hibernate 3.6.5 final, the testing database is HSQLDB.</p>
  
  <p>UPDATE: Seems like a bug to me too, and indeed may be not related to the injected SQL. Tried setting the id with a nonexistent value and also returns all the rows. Tried the injection with '5'='5' instead of '1'='1' and the 5 is not propagated to the SQL call. It keeps using (1=1) as where clause.</p>
  
  <p>UPDATE 2: Solved. See the answer below.</p>