title: How to validate JPQL (JPA query) programmatically
body: <p>I am looking for a way to validate JPA query programmatically.</p>
  
  <p>Within a (Spring) transaction, I have a list of queries to run. These queries can contain syntax errors which I would like to catch so that the transaction can continue.</p>
  
  <p>My first idea was to use the <code>EntityManager</code> and create and execute my queries, and in case they fail, then I could simply catch the exception, log a warning and continue.</p>
  
  <p>The problem is that when a problem occurs, the transaction is flagged for rollbackOnly so my current transaction is rolled back which is not what I want.</p>
  
  <p>In pseudo code, it goes more or less like this:</p>
  
  <pre><code>  EntityManager em = ...;
    em.getTransaction().begin();
    List&lt;String&gt; queries = Arrays.asList("select e from Department d", 
               "select d from Department d");
    for(String query:queries) {
         TypedQuery&lt;Department&gt; typedQuery = em.createQuery(query, Department.class); // This can throw an exception
         List&lt;Department&gt; deps = typedQuery.getResultList(); // This can also throw an exception
         //... do some stuff with the departements
    }
  </code></pre>
  
  <p>The alternative I found so far was to create another <code>EntityManager</code> from the original one (<code>em.getEntityManagerFactory().createEntityManager()</code>), run first my queries in that one and then re-execute them (in case of success) in the original one, but this is really not efficient and looks quite ugly.</p>
  
  <p>I am using EclipseLink as a JPA implementation and I cannot switch to another JPA implementation.</p>