简体   繁体   中英

JPQL: Enum literal in SELECT NEW query

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();

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)

I use EclipseLink as persistence framework.

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

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_path_expression
  • scalar_expression
  • aggregate_expression
  • identification_variable

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