我有以下类(class)
@NamedQueries({
@NamedQuery(name = "User.FindByFilter", query = "SELECT NEW myPkg.SimpleUser(u.name , u.email, u.roles) FROM User u WHERE UPPER(u.name) LIKE :filter AND ORDER BY u.name")
})
@Entity
@Table(name = "Users")
public class User implements Serializable, UserDetails {
@Id
private String email;
@Basic
private String name;
@OneToMany(cascade = { CascadeType.REFRESH, CascadeType.PERSIST }, fetch = FetchType.EAGER)
private Set<Authority> roles;
...
}
和
@Entity
public class Authority implements GrantedAuthority {
//just @Id and @Basic here no specific mapping back to user
...
}
我当然知道这个查询
@NamedQuery(name = "User.FindByFilter", query = "SELECT NEW myPkg.SimpleUser(u.name , u.email, u.roles) FROM User u WHERE UPPER(u.name) LIKE :filter AND ORDER BY u.name")
是错误的,因为u.roles
是@OneToMany
。
所以我的问题是将 Roles 字段传递给 const 的正确方法是什么?
最佳答案
来自JPA 2.0 specification ,它使用 single_valued_object_field
和 collection_valued_field
分别表示单个实体字段和集合实体字段:
A single_valued_object_field is designated by the name of an association field in a one-to-one or many-to-one relationship or a field of embeddable class type. The type of a single_valued_object_field is the abstract schema type of the related entity or embeddable class.
A collection_valued_field is designated by the name of an association field in a one-to-many or a many-to-many relationship or by the name of an element collection field. The type of a collection_valued_field is a collection of values of the abstract schema type of the related entity or element type.
然后它定义了具有以下语法的 SELECT 子句:
constructor_expression ::= NEW constructor_name ( constructor_item {, constructor_item}* )
constructor_item ::= single_valued_path_expression | scalar_expression | aggregate_expression | identification_variable
由于 constructor_item
可以接受 single_valued_path_expression
但不能接受 collection_valued_field
,我认为 new()
不能接受集合字段参数。
您必须使用 fetch 连接来检索 User
实例及其 Authority
集合,然后手动将其转换为 myPkg.SimpleUser
关于java - 将一对多文件传递给 NEW-Statement 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063616/