这是可能的:结果中的list属性的JPA/Hibernate查询?

Kde*_*per 13 hibernate jpa hql jpql jpa-2.0

在hibernate中我想运行这个JPQL/HQL查询:

select new org.test.userDTO( u.id, u.name, u.securityRoles)
FROM User u
WHERE u.name = :name
Run Code Online (Sandbox Code Playgroud)

userDTO类:

public class UserDTO {
   private Integer id;
   private String name;
   private List<SecurityRole> securityRoles;

   public UserDTO(Integer id, String name, List<SecurityRole> securityRoles) {
     this.id = id;
     this.name = name;
     this.securityRoles = securityRoles;
   }

   ...getters and setters...
}
Run Code Online (Sandbox Code Playgroud)

用户实体:

@Entity
public class User {

  @id
  private Integer id;

  private String name;

  @ManyToMany
  @JoinTable(name = "user_has_role",
      joinColumns = { @JoinColumn(name = "user_id") },
      inverseJoinColumns = {@JoinColumn(name = "security_role_id") }
  )
  private List<SecurityRole> securityRoles;

  ...getters and setters...
}
Run Code Online (Sandbox Code Playgroud)

但是当Hibernate 3.5(JPA 2)启动时,我收到此错误:

org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate 
constructor on class [org.test.UserDTO] [SELECT NEW org.test.UserDTO (u.id,
u.name, u.securityRoles) FROM nl.test.User u WHERE u.name = :name ]
Run Code Online (Sandbox Code Playgroud)

是否包含列表(u.securityRoles)的select不可能?我应该创建2个单独的查询吗?

Pas*_*ent 10

没有NEW(选择标量值集合值路径表达式)的查询无效,所以我不认为添加一个NEW会使事情有效.

为了记录,这是JPA 2.0规范在4.8 SELECT子句中所述的内容:

SELECT子句具有以下语法:

select_clause ::= SELECT [DISTINCT] select_item {, select_item}*
select_item ::= select_expression [ [AS] result_variable]
select_expression ::=
         single_valued_path_expression |
         scalar_expression |
         aggregate_expression |
         identification_variable |
         OBJECT(identification_variable) |
         constructor_expression
constructor_expression ::=
         NEW constructor_name ( constructor_item {, constructor_item}* )
constructor_item ::=
         single_valued_path_expression |
         scalar_expression |
         aggregate_expression |
         identification_variable
aggregate_expression ::=
         { AVG | MAX | MIN | SUM } ([DISTINCT] state_field_path_expression) |
         COUNT ([DISTINCT] identification_variable | state_field_path_expression |
                  single_valued_object_path_expression)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我应该在JPA规范中查看它.显然,u.securityRoles不是'single_valued_pa​​th_expression'.所以我想这意味着,必须对检索集合/关系进行单独的查询(或使用连接并使用循环创建集合). (2认同)