简体   繁体   English

如何以编程方式验证JPQL(JPA查询)

[英]How to validate JPQL (JPA query) programmatically

I am looking for a way to validate JPA query programmatically. 我正在寻找一种以编程方式验证JPA查询的方法。

Within a (Spring) transaction, I have a list of queries to run. 在(Spring)事务中,我有一个要运行的查询列表。 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. 我的第一个想法是使用EntityManager并创建并执行我的查询,如果它们失败,那么我可以简单地捕获异常,记录警告并继续。

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. 问题是,当出现问题时,事务被标记为rollbackOnly,因此我的当前事务被回滚,这不是我想要的。

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. 到目前为止,我发现的替代方法是从原始的创建另一个EntityManagerem.getEntityManagerFactory().createEntityManager() ),首先运行我的查询,然后在原始的中重新执行它们(如果成功) ,但这真的不高效,看起来很难看。

I am using EclipseLink as a JPA implementation and I cannot switch to another JPA implementation. 我使用EclipseLink作为JPA实现,我无法切换到另一个JPA实现。

I suppose you want complile-time validation for JPQL. 我想你想要JPQL的complile-time验证。 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. 为了完成您想要的工作,请使用标准api而不是JPQL。 Check the documentation for the criteria api. 检查文档中的条件api。 You will need to user metamodel for compile-time checking 您需要使用元模型进行编译时检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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