I have the following tables:
USER
ID VARCHAR(32) INTEGER NOT NULL
ROLE
ID INTEGER NOT NULL
USERROLE /*Many to Many*/
USER_ID VARCHAR(32) NOT NULL
ROLE_ID INTEGER NOT NULL
and I’m using annotations to Map the DB Tables to my Classes.
/* Mapping for USER table */
@Entity
@Table (name="USER")
public class User{
@Id
@Column (name="ID")
private String id;
@ManyToMany
@JoinTable (name="USERROLE", joinColumns = {@JoinColumn (name="USER_ID")},
inverseJoinColumns = {@JoinColumn (name="ROLE_ID")})
@LazyCollection (LazyCollectionOption.FALSE)
private List<Role> roles;
}
/* Mapping for ROLE table */
@Entity
@Table (name="ROLE")
public class Role {
@Id
@Column (name="ID")
private int id;
}
Now I would like to do a query that Joins ROLE and USERROLE tables so that i could get those ROLEs that has user assigned to it.
–EDIT
I have the Role.id, and I want to check whether this Role is being referenced in the USERROLE table. in native SQL, I would do it this way:
SELECT DISTINCT A.* from ROLE A INNER JOIN USERROLE B
WHERE A.ID = B.ROLE_ID AND A.ID = ?;
how to do it in hibernate using HibernateTemplate?
It’s pretty easy:
Or even simpler, without any query:
EDIT : to know if a given role is referenced by at least one user, you can use the following query, which is very similar to your SQL query: