Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL: Hibernate query with ManyToMany

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.

like image 216
Kiva Avatar asked Aug 13 '10 08:08

Kiva


People also ask

What is query uniqueResult () in hibernate?

uniqueResult() Convenience method to return a single instance that matches the query, or null if the query returns no results.

Does hibernate support union HQL query?

I know hibernate does not support union queries at the moment, right now the only way I see to make a union is to use a view table.

Is HQL and JPQL same?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.


2 Answers

This should do it:

from Portailuser u join u.portailroles r where r.name=:roleName
like image 58
Maurice Perry Avatar answered Oct 18 '22 19:10

Maurice Perry


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 + "'")
like image 41
dezhi.shen Avatar answered Oct 18 '22 21:10

dezhi.shen