我希望有多对多的关系。在PLAYER
和PRIVILEGE
之间。你能帮我修一下我的.xml配置吗?
预期结果:
我希望能够执行:String hql = "from Player as p right outer join p.privilages as priv";
实际: 到目前为止,我得到了:
org.hibernate.MappingException:外键(FK8CD18EE134F64423:PLAYER [ID]))必须具有与引用的主键相同的列数 (特权[ID,PRIVILAGE])
<hibernate-mapping>
<class name="model.Privilage" table="PRIVILAGE">
<id name="id" type="int" >
<column name="ID" precision="5" scale="0"/>
<generator class="increment"/>
</id>
<set name="players" table="PLAYER"
inverse="false" lazy="true" fetch="select" cascade="all" >
<key>
<column name="ID"/>
</key>
<many-to-many entity-name="model.Player">
<column name="ID" not-null="true" />
</many-to-many>
</set>
<property name="privilage" type="string">
<column name="PRIVILAGE" length="20" not-null="true" />
</property>
</class>
</hibernate-mapping>
和
<class name="model.Player" table="PLAYER">
<id name="playerId" type="int" >
<column name="ID" precision="5" scale="0"/>
<generator class="sequence">
<param name="sequence">PLAYER_SEQ</param>
</generator>
</id>
<set name="privilages" table="PRIVILAGE"
inverse="false" lazy="true" fetch="select" cascade="all" >
<key>
<column name="ID"/>
</key>
<many-to-many entity-name="model.Privilage">
<column name="PRIVILAGE" not-null="true" />
</many-to-many>
</set>
<!-- ... -->
</class>
答案 0 :(得分:3)
您应该引用名为PLAYER_PRIV的多对多关系表:
<set name="privilages" table="PLAYER_PRIV"
inverse="true" lazy="true" fetch="select">
<key>
<column name="ID"/>
</key>
<many-to-many entity-name="model.Privilage">
<column name="PRIV_ID" not-null="true"/>
</many-to-many>
</set>
和
<set name="players" table="PLAYER_PRIV"
inverse="false" lazy="true" fetch="select">
<key>
<column name="ID"/>
</key>
<many-to-many entity-name="model.Player">
<column name="PLAYER_ID" not-null="true"/>
</many-to-many>
</set>
答案 1 :(得分:0)
您正在映射错误的关联表名称及其列。
1)双方的关联表是相同的(PLAYER_PRIV
):
<set name="privilages" table="PLAYER_PRIV"
...
</set>
<set name="players" table="PLAYER_PRIV"
...
</set>
2)Privilage
映射中的列:
<key>
<column name="PRIV_ID"/>
</key>
<many-to-many entity-name="model.Player">
<column name="PLAYER_ID" not-null="true" />
</many-to-many>
在Player
映射中,情况正好相反:
<key>
<column name="PLAYER_ID"/>
</key>
<many-to-many entity-name="model.Privilage">
<column name="PRIV_ID" not-null="true" />
</many-to-many>
3)除此之外,您必须选择一方为inverse
。来自documentation:
如果关联是双向的,则一方必须是所有者和 一方必须是反向结束(即,当它被忽略时 更新关联表中的关系值。)
4)您可能不想在多对多关联中使用cascade=all
,因为在删除权限时您可能不想删除所有权限的所有玩家理所当然的。