Hibernate many-to-many的查询

原文地址:http://blog.csdn.net/ebookbug/article/details/407130

有三个表user,role,user_role.user和role通过user-role进行多对多关联,
user类role类,及映射文件如下

import java.util.*;

public class User implements java.io.Serializable {
private int id;
private String username;
private Set SetOfUserRole;

private void setId (int id) {
this.id = id;
}

public int getId() {
return id;
}

public void setUsername(String name) {
this.username = name;
}

public String getUsername() {
return username();
}

public Set getSetOfUserRole () {
return this.SetOfUserRole;
}

public void setSetOfUserRole (Set SetOfUserRole) {
this.SetOfUserRole = SetOfUserRole;
}

}

public class Role implements java.io.Serializable {
private int id;
private String rolename;
private Set SetOfUserRole;

private void setId (int id) {
this.id = id;
}

public int getId() {
return id;
}

public void setRolename(String name) {
this.rolename = name;
}

public String getRolename() {
return rolename();
}

public Set getSetOfUserRole () {
return this.SetOfUserRole;
}

public void setSetOfUserRole (Set SetOfUserRole) {
this.SetOfUserRole = SetOfUserRole;
}

}



"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



name="User"
table="user"
schema="dbo"
lazy="false"
>
name="Id"
type="int"
>




name="username"
type="java.lang.String"
>



name="SetOfUserrole"
table="user_role"
lazy="true"
inverse="false"
cascade="save-update"
>



class="Role"
column="role_id"
outer-join="auto"
/>







"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



name=Role"
table="role"
schema="dbo"
lazy="false"
>
name="Id"
type="int"
>




name="username"
type="java.lang.String"
>



name="SetOfUserrole"
table="user_role"
lazy="true"
inverse="false"
cascade="save-update"
>



class="User"
column="user_id"
outer-join="auto"
/>





我想查找roleid为1,2,3的用户,并且按用户名排序,如何用hql查询?

select user from User as user left join user.SetOfUserRole as role
where role.id in (1,2,3)  order by user.username

其实就是把set可以当作set中的对象来读取

 

 

 

 

你可能感兴趣的:(hibernate,user,class,string,generator,table,java)