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.
uniqueResult() Convenience method to return a single instance that matches the query, or null if the query returns no results.
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.
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.
This should do it:
from Portailuser u join u.portailroles r where r.name=:roleName
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 + "'")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With