简体   繁体   中英

How to validate JPQL (JPA query) programmatically

I am looking for a way to validate JPA query programmatically.

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.

My first idea was to use the EntityManager and create and execute my queries, and in case they fail, then I could simply catch the exception, log a warning and continue.

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.

In pseudo code, it goes more or less 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 found so far was to create another EntityManager from the original one ( em.getEntityManagerFactory().createEntityManager() ), 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.

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

I suppose you want complile-time validation for JPQL. There is no way to check if the query syntax is correct.

In order to do the job you want, use the criteria api instead of JPQL. Check the documentation for the criteria api. You will need to user metamodel for compile-time checking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM