日期:2014-05-19  浏览次数:20659 次

Hibernate多对多查询
public class Group extends BaseEntity {
private String name; // 用户组名
private String describe;
private Set<Role> roles=new HashSet<Role>(); //组与角色(多对多)
  .....
}
public class Role extends BaseEntity {
private String name; // 角色名
private String lxDescribe;
private Set<Group> groups = new HashSet<Group>(); // 角色与组(多对多)
  ...
}
<hibernate-mapping>
<class name="com.lxitedu.entity.group.Group" table="LXGroup" lazy="false">
<id name="id" type="long">
<generator class="native"></generator>
</id>
<property name="name" column="LXName"></property>
<property name="describe" column="LXDescribe"></property>
<set name="roles" table="role_group" cascade="all">
<key column="group_id"></key>
<many-to-many column="role_id" class="com.lxitedu.entity.role.Role"></many-to-many>
</set>
</class>
</hibernate-mapping>

<hibernate-mapping>
<class name="com.lxitedu.entity.role.Role" table="LxRole" lazy="false">
<id name="id" type="long">
<generator class="native"></generator>
</id>
<property name="name" type="java.lang.String"></property>
<property name="lxDescribe" type="java.lang.String" column="lxDescribe"></property>
<set name="groups" table="role_group">
<key column="role_id"></key>
<many-to-many column="group_id" class="com.lxitedu.entity.group.Group"></many-to-many>
</set>
<set name="users" table="role_user" inverse="true" cascade="all">
<key column="role_id"></key>
<many-to-many column="user_id" class="com.lxitedu.entity.user.User"/>
</set>
</class>
</hibernate-mapping>

多对多,我保存做好了了,但是多对多的查询不知道做?那位大哥知道告诉我,分少了我就再加!
public List getAllGroup() {
  return getHibernateTemplate().loadAll(Group.class);
 }
这样做对不对?好像不能查出来


------解决方案--------------------
首先要告诉你,你的思路都错了
如果要是在数据库端设计
用户组和角色之间是多对多的关联关系,这两张表之间最好不要直接关联,应该设置一张关联表来表达用户组表与角色表之间的关联,
这样在Hibernate中,设置的时候,用户组实体与关联对象之间关联(多对一),角色也与关联对象关联(多对一),这样设计就比较清楚了。
当你打算做多对多关联的时候,必须要设置一个关联表,这样做才最合理。
------解决方案--------------------
many-to-many
------解决方案--------------------
最好说清楚要查什么
------解决方案--------------------
我没用过你设置的这个方法,再说你这里边有很大的问题
<set name="groups" table="role_group"> 
<key column="role_id"> </key> 
<many-to-many column="group_id" class="com.lxitedu.entity.group.Group"> </many-to-many> 
</set>
你这里group_id的类型应该是个集合吧,集合中存在的类型应该是关联类的类型,可这里边你写的还是组类型

建议
用户组配置文件
<set name="groups"> 
<key column="role_id"> </key> 
<on-to-many column="group_id" class="com.lxitedu.entity.group.Role_Group"> </many-to-many> 
</set>

关联配置文件
<many-to-one>

用户角色采用
<set>
<on-to-many>
</set>

要特别注意集合中放置的是什么类型