JPQL: Enum literal in SELECT NEW query

纵然是瞬间 提交于 2019-12-30 06:34:46

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/8503845/jpql-enum-literal-in-select-new-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!