本文介绍了这是可能的:JPA / Hibernate查询结果中的列表属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  select new org。 test.userDTO(u.id,u.name,u.securityRoles)
FROM用户u
其中u.name =:name

userDTO class:

  public class UserDTO {
private Integer ID;
私人字符串名称;
私人列表< SecurityRole> securityRoles;
$ b $ public UserDTO(Integer id,String name,List< SecurityRole> securityRoles){
this.id = id;
this.name = name;
this.securityRoles = securityRoles;
}

...获得者和设置者...
}

用户实体:

  @Entity 
公共类用户{

@id
私人整数ID;

私人字符串名称;

@ManyToMany
@JoinTable(name =user_has_role,
joinColumns = {@JoinColumn(name =user_id)},
inverseJoinColumns = {@JoinColumn (name =security_role_id)}

private List< SecurityRole> securityRoles;

...获得者和设置者...
}

但是当Hibernate 3.5(JPA 2)启动时,我得到这个错误:

  org.hibernate.hql.ast.QuerySyntaxException:Unable在类[org.test.UserDTO]上找到合适的
构造函数[SELECT new org.test.UserDTO(u.id,
u.name,u.securityRoles)FROM nl.test.User u WHERE u.name =:name]

是一个包含列表的选择(u.securityRoles )因此不可能?我应该创建2个单独的查询吗?

解决方案

code>(选择标量值集合值路径表达式)无效,所以我不认为添加 NEW 会使事情发挥作用。 为了记录,这就是JPA 2.0规范在 4.8 SELECT子句部分所说的内容:


In hibernate I want to run this JPQL / HQL query:

select new org.test.userDTO( u.id, u.name, u.securityRoles)
FROM User u
WHERE u.name = :name

userDTO class:

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...
}

User Entity:

@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...
}

But when Hibernate 3.5 (JPA 2) starts I get this error:

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 ]

Is a select that includes a list (u.securityRoles) as a result not possible? Should I just create 2 seperate queries?

解决方案

The query without the NEW (selecting a scalar value and a collection-valued path expression) isn't valid so I don't think that adding a NEW will make things work.

For the record, this is what the JPA 2.0 specification says in the section 4.8 SELECT Clause:

这篇关于这是可能的:JPA / Hibernate查询结果中的列表属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:19