How to write a HQL query for Many To Many Associations?

Viewed 16696

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.

I just wanted the association as unidirectional. i.e: Roles--->Tokens So the annotation in the Role class looks like,

@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.

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.

How shall i get tokenName itself? Actually my problem is solved, but i would like to know how to do it.

It ll be helpful to me, if anyone explains the Query Construction.

Any suggestions!!

2 Answers
Related