1

我正在尝试在 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”标签,但它仍然不会保存在数据库中。

4

1 回答 1

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 映射必须是这样的:

在授权主体中:

<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>
于 2012-05-30T19:08:19.393 回答