Java ElementCollection 的 JPQL 选择查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21924918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPQL select query for ElementCollection
提问by Zaw Than oo
I have the following entity with enum
collection. I would like to search the user with an enum
parameter.
The user might have multiple permission. When I search the users with the parameter like Permission.APPROVE
, there may be one or more user who have that permission.
How can I write JPQL
query?
我有以下enum
收藏实体。我想用enum
参数搜索用户。
用户可能有多个权限。当我使用类似参数搜索用户时Permission.APPROVE
,可能有一个或多个用户拥有该权限。我该如何编写JPQL
查询?
User.java
用户.java
@Entity
....
public class User implements Serializable {
@ElementCollection(targetClass = Permission.class)
@Enumerated(EnumType.STRING)
@CollectionTable(name = "USER_PERMISSION", joinColumns = @JoinColumn(name = "PERMISSION", referencedColumnName = "ID"))
private List<Permission> permisssionList;
}
Permission.java
权限.java
public enum Permission {
REGISTER, APPROVE, REJECT, CONFIRM;
}
How to write ?
怎么写 ?
public List<User> findUserList(Permission permission) {
Query q = em.createQuery(.....);
result = q.getResultList();
}
采纳答案by Koitoer
From spec
从规格
Enum literals support the use of Java enum literal syntax. The fully qualified enum class name must be specified.
枚举文字支持使用 Java 枚举文字语法。必须指定完全限定的枚举类名。
select u from User u where u.Permission = XX.XX.Permission.APPROVE
Try this one.
试试这个。
String jpql =
"select u from User u join u.permission p"
+ " where p = :enumeration";
Query query = em.createQuery(jpql);
query.setParameter("enumeration", XX.XX.Permission.APPROVE);
回答by Camilo
@Embeddable
and @CollectionTable
are just a simple way to map One To Many relationships, they can not be queried directly nor persisted, but certainly can be joined, do it like you would with any One To Many relationship:
@Embeddable
并且@CollectionTable
只是映射一对多关系的一种简单方法,它们不能直接查询也不能持久化,但当然可以加入,就像处理任何一对多关系一样:
"select user from User user join user.permissionList p where p = :permission"
and pass the enum as a regular parameter
并将枚举作为常规参数传递