Hibernate hbm有很多对很多的映射

时间:2012-05-30 16:19:39

标签: database hibernate many-to-many save hbm

我正在尝试在2个对象之间创建一对多映射(使用Java)。我能够保存数据库中的对象,但不能保存它们之间的关系。我有一个名为“AuthorizationPrincipal”的类,它包含一组“权限”

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="org.openmrs">

<class name="AuthorizationPrincipal" table="authorization_principal" lazy="false">


<id
    name="authorizationPrincipalId"
    type="int"
    column="authorization_principal_id"
    unsaved-value="0"
>
    <generator class="native" />
</id>

<discriminator column="authorization_principal_id" insert="false" />


<property name="name" type="java.lang.String" column="name" unique="true"
            length="38"/>


<many-to-one
    name="creator"
    class="org.openmrs.User"
    not-null="true"
/>

<property
    name="uuid"
    type="java.lang.String"
    column="uuid"
    length="38"
    unique="true"
/>
<property
    name="dateCreated"
    type="java.util.Date"
    column="date_created"
    not-null="true"
    length="19"
/>
<property
    name="policy"
    type="java.lang.String"
    column="policy"
    not-null="true"
    length="255"
/>

<!--  Associations -->

<set name="privileges" inverse="true" cascade=""
    table="authorization_principal_privilege" >
    <key column="authorization_principal_id" not-null="true"/>
    <many-to-many class="Privilege">
        <column name="privilege" not-null="true" />
    </many-to-many>
</set>

</class>

我通过以下几个教程和示例提出了“set”标记,但它仍然无法保存在数据库中。

1 个答案:

答案 0 :(得分:1)

我看到错误的第一件事是您将关系定义为来自AuthorizationPrincipal实体的多对多,正如您在问题中所说,您想要一对多的关系。

然后,你必须像这样定义你的集合:

<set name="privileges" inverse="true" cascade="all,delete-orphan">
    <key column="authorization_principal_id" not-null="true" />
    <one-to-many class="Privileges" />
</set>

此配置应该足够了。

修改

如果您的配置是多对多的,那么您必须拥有 AuthoririzationPrincipal 权限之间关系的表,例如 AuthoririzationPrincipal-Privileges

ypur映射必须如下:

在AuthorizationPrincipal中:

<set name="privileges" table="AuthoririzationPrincipal-Privileges">
    <key column="authorization_principal_id" />
    <many-to-many class="Privileges" column="privileges_id" />
</set>

并且在特权中:

<set name="authorizationPrincipals" inverse="true" table="AuthoririzationPrincipal-Privileges">
    <key column="privileges_id" />
    <many-to-many class="AuthoririzationPrincipal" column="authorization_principal_id" />
</set>