Java HQL:使用 ManyToMany 进行休眠查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3475171/
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
HQL: Hibernate query with ManyToMany
提问by Kiva
I have a question with HQL query and hibernate.
我有一个关于 HQL 查询和休眠的问题。
I have a user class and a role class. A user can have many roles. So I have a ManyToMany relatation like this:
我有一个用户类和一个角色类。一个用户可以有多个角色。所以我有一个像这样的多对多关系:
In user class:
在用户类中:
@ManyToMany(fetch = FetchType.LAZY)
@oinTable(name = "PORTAIL_USERROLE", joinColumns = { @JoinColumn(name = "USERID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "ROLE", nullable = false, updatable = false) })
public Set<Portailrole> getPortailroles() {
return this.portailroles;
}
In role class:
在角色类中:
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "PORTAIL_USERROLE", joinColumns = { @JoinColumn(name = "ROLE", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "USERID", nullable = false, updatable = false) })
public Set<Portailuser> getPortailusers() {
return this.portailusers;
}
This mapping has created a 3rd table (PORTAIL_USERROLE) where relations are stocked. All work fine like this. When I have a user, I retrieve roles.
此映射创建了第三个表 (PORTAIL_USERROLE),其中存储了关系。像这样一切正常。当我有一个用户时,我检索角色。
But, my question is: in a HQL query, how can I get all users which have a specific role ? Any class represents PORTAIL_USERROLE table so I don't know how to make my HQL query.
但是,我的问题是:在 HQL 查询中,如何获取具有特定角色的所有用户?任何类都代表 PORTAIL_USERROLE 表,所以我不知道如何进行 HQL 查询。
采纳答案by Maurice Perry
This should do it:
这应该这样做:
from Portailuser u join u.portailroles r where r.name=:roleName
回答by dezhi.shen
you can use @WhereJoinTable Like this:
你可以像这样使用@WhereJoinTable:
@JoinTable(name = "OFFICE_USER_POSITION", joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {
@JoinColumn(name = "POST_ID", referencedColumnName = "id")})
@WhereJoinTable(clause = "primary_flag='" + YES + "' and del_flag='" + DEL_FLAG_NORMAL + "'")