HQL: Hibernate query with ManyToMany

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

I have a question with HQL query and hibernate.

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.

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.

回答1:

This should do it:

from Portailuser u join u.portailroles r where r.name=:roleName 


回答2:

you can use @WhereJoinTable Like this:

 @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 + "'") 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!