java 如何为多对多关联编写 HQL 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3816502/
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
How to write a HQL query for Many To Many Associations?
提问by axtavt
I have 3 tables, Role[roleId, roleName]
, Token[tokenID, tokenName]
& ROLETOKENASSOCIATION[roleId, tokenID]
. The 3rd one was created automatically by hibernate. Now if i simply write a Query to get all the objects from Role class means, it gives the all role objects along with the associated tokenID & tokenName.
我有 3 个表,Role[roleId, roleName]
, Token[tokenID, tokenName]
& ROLETOKENASSOCIATION[roleId, tokenID]
。第三个是由休眠自动创建的。现在,如果我简单地编写一个查询来从 Role 类中获取所有对象,它会提供所有角色对象以及相关联的 tokenID 和 tokenName。
I just wanted the association as unidirectional. i.e: Roles--->Tokens So the annotation in the Role class looks like,
我只是希望关联是单向的。即:Roles--->Tokens 所以Role类中的注解是这样的,
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int roleId;
private String roleName;
@ManyToMany
@JoinTable(name="ROLE_TOKEN_ASSOCIATION",
joinColumns={@JoinColumn(name="roleId")},
inverseJoinColumns={@JoinColumn(name="tokenID")})
private List<Token> tkns;
//Getters & Setters
Now i want the tokenNames for the specific roleId.
First i made a query like this SELECT tkns.tokenName FROM Role WHERE Role.roleId=:roleId
But, i ended up with some dereference error.
现在我想要特定 roleId 的 tokenNames。首先我做了一个这样的查询SELECT tkns.tokenName FROM Role WHERE Role.roleId=:roleId
但是,我最终遇到了一些取消引用错误。
Then i changed the query to SELECT tkns FROM Role r WHERE r.roleId=:roleId
Now i have got what i wanted. But it comes with roleId too.
然后我将查询更改为SELECT tkns FROM Role r WHERE r.roleId=:roleId
现在我得到了我想要的。但它也带有 roleId。
How shall i get tokenName itself? Actually my problem is solved, but i would like to know how to do it.
我该如何获得 tokenName 本身?其实我的问题已经解决了,但我想知道怎么做。
It ll be helpful to me, if anyone explains the Query Construction.
如果有人解释查询构造,这将对我有所帮助。
Any suggestions!!
有什么建议!!
回答by axtavt
Have you tried
你有没有尝试过
SELECT t.tokenName FROM Role r JOIN r.tkns t WHERE r.roleId = :roleId
EDIT:This query almost directly maps to the corresponding SQL query where Role r JOIN r.tkns t
is a shorthand syntax for the SQL join via the link table Role r JOIN ROLETOKENASSOCIATION rt ON r.roleId = rt.roleId JOIN Token ON rt.tokenId = t.tokenId
. Affe's answer is another syntax for the same query.
编辑:此查询几乎直接映射到相应的 SQL 查询,其中Role r JOIN r.tkns t
是通过链接表的 SQL 连接的简写语法Role r JOIN ROLETOKENASSOCIATION rt ON r.roleId = rt.roleId JOIN Token ON rt.tokenId = t.tokenId
。Affe 的回答是相同查询的另一种语法。
See also:
也可以看看:
回答by Affe
You want a scalar list of just the name field? You should be able to get that like this
你想要一个只有 name 字段的标量列表?你应该能够得到这样的
select t.name from Roles r, IN(r.tkns) t where r.roleId = :id