How to validate JPQL (JPA query) programmatically

I am looking for a way to test a JPA request programmatically.

In a transaction (Spring), I have a list of queries to run. These queries may contain syntax errors that I would like to catch for the transaction to continue.

My first idea was to use the EntityManager and create and execute my requests, and if they failed, I could just catch the exception, log a warning and continue.

The problem is that when a problem occurs, the transaction is marked for rollbackOnly, so my current transaction rolls back, which is not what I want.

In pseudocode, it more or less looks like this:

  EntityManager em = ...; em.getTransaction().begin(); List<String> queries = Arrays.asList("select e from Department d", "select d from Department d"); for(String query:queries) { TypedQuery<Department> typedQuery = em.createQuery(query, Department.class); // This can throw an exception List<Department> deps = typedQuery.getResultList(); // This can also throw an exception //... do some stuff with the departements } 

The alternative I have found so far was to create another EntityManager from the source ( em.getEntityManagerFactory().createEntityManager() ), first run my queries in this, and then repeat them (if successful) in the original, but it really inefficient and looks pretty ugly.

I am using EclipseLink as a JPA implementation and I cannot switch to another JPA implementation.

+7
java spring jpa eclipselink jpql
source share
1 answer

I assume you need a runtime check for JPQL. Unable to validate query syntax.

To complete the task you want, use api criteria instead of JPQL. Check the documentation for api criteria. You will need a user metamodel to check compile time

0
source share

All Articles