JPQL:SELECT NEW查询中的枚举文字

问题描述:

我有几个域类的描述符类。描述符类有一个字段'type',它是一个枚举,表示域类的类型。在一些查询中,我想返回或更多描述符,并将类型作为构造函数参数传递。所以我的想法是将它作为查询参数传递:

I have a descriptor class for a couple of domain classes. The descriptor class has a field 'type' which is an enum and indicates the type of the domain class. In some queries I want to return on or more descriptors and pass the type as constructor argument. So my idea was to pass it as a query parameter:

  String jpql = "SELECT NEW model.ModelDescriptor"
    + "(t.id, t.name, t.description, :modelType) ... ";
  TypedQuery<ModelDescriptor> query = em.createQuery(jpql, ModelDescriptor.class);
  query.setParameter("modelType", ModelType.forClass(clazz));
  List<ModelDescriptor> list = query.getResultList();

这不起作用。不会抛出异常,但结果中的类型为 null 。此外,无法将枚举文字传递给查询:

This does not work. No exception is thrown but the type is null in the results. Also it is not possible to pass the enum literal to the query:

  "SELECT NEW model.ModelDescriptor (f.id, f.name, f.description,   
    model.ModelType.FLOW) ... "

编辑
我得到以下堆栈跟踪:

edit I get the following stack trace:

  java.lang.IllegalArgumentException: An exception occurred while creating a query in 
  EntityManager: 
  Exception Description: Error compiling the query [SELECT model.ModelDescriptor(f.id,
  f.name, f.description, model.ModelType.FLOW) FROM Flow f WHERE flow.id = :flowId], 
  line 1, column 78: unknown identification variable [model]. The FROM clause of the
  query does not declare an identification variable [model].
  at org.eclipse.persistence.internal.jpa.EntityManagerImpl.
         createQuery(EntityManagerImpl.java:1477)
  at org.eclipse.persistence.internal.jpa.EntityManagerImpl.
          createQuery(EntityManagerImpl.java:1497)

我使用EclipseLink作为持久性框架。

I use EclipseLink as persistence framework.

有没有办法将枚举文字传递给SELECT NEW表达式?

Is there a way to pass an enum literal into an SELECT NEW expression?

没有,通常没有办法引用任何类中的字段,也无法将参数传递给SELECT子句。只有构造函数表达式的有效参数是(来自JPA 2.0规范,第174页)

No there is not, in general there is no way to reference to the fields in any class and it is also not possible to pass argument to the SELECT clause. Only valid arguments to the constructor expression are (from JPA 2.0 specification, page 174)


  • single_valued_pa​​th_expression

  • scalar_expression

  • aggregate_expression

  • identification_variable

  • single_valued_path_expression
  • scalar_expression
  • aggregate_expression
  • identification_variable