hibernate多对多级联查询问题
三张表 role, role_privilege, privilege,中间表只有两个字段
为另两张表的id做联合主键
Role.hbm.xml
程序代码:
<hibernate-mapping> <class name="com.jeff.domain.Role" table="role" catalog="demo"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="increment" /> </id> <property name="rolename" type="java.lang.String"> <column name="rolename" length="100" not-null="true" /> </property> <set name="users" inverse="true" lazy="false"> <key column="rid"></key> <one-to-many class="com.jeff.domain.Users" /> </set> <set name="privilege" table="role_privilege" inverse="true" lazy="false"> <key> <column name="pid"></column> </key> <many-to-many entity-name="com.jeff.domain.Privilege" column="id"></many-to-many> </set> </class> </hibernate-mapping>
Privilege.hbm.xml
程序代码:
<hibernate-mapping> <class name="com.jeff.domain.Privilege" table="privilege" catalog="demo"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="increment" /> </id> <property name="privilegename" type="java.lang.String"> <column name="privilegename" length="100" not-null="true" /> </property> <set name="role" table="role_privilege" lazy="false"> <key> <column name="rid"></column> </key> <many-to-many entity-name="com.jeff.domain.Role" column="id"></many-to-many> </set> </class> </hibernate-mapping>
级联查询时出错
Exception in thread "main" org.springframework.dao.InvalidDataAccessResourceUsageException: could not initialize a collection: [com.jeff.domain.Role.privilege#1]; SQL [select privilege0_.pid as pid1_, privilege0_.id as id1_, privilege1_.id as id3_0_, privilege1_.privilegename as privileg2_3_0_ from role_privilege privilege0_ left outer join demo.privilege privilege1_ on privilege0_.id=privilege1_.id where privilege0_.pid=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not initialize a collection: [com.jeff.domain.Role.privilege#1]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
看了出错的查询语句:如上红色部分
select
privilege0_.pid as pid1_,
privilege0_.id as id1_, //这里居然会查中间表的ID 中间表根本没有ID啊。。。。
privilege1_.id as id3_0_,
privilege1_.privilegename as privileg2_3_0_
from
role_privilege privilege0_ left outer join demo.privilege privilege1_
on
privilege0_.id=privilege1_.id
where
privilege0_.pid=?
用的mysql数据库
为这问题愁一天了, 谁帮解决下