質問

I am trying to create a one-to-many mapping between 2 objects (work with Java). I am able to save the objects in the database, but not their relationship. I have a class called "AuthorizationPrincipal" and it contains a set of "Privileges"

<?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>

I came up with the "set" tag by following through a few tutorials and examples, but it still won't save in the database.

役に立ちましたか?

解決

The first thing I see wrong is that you defined the relationship as a many-to-many from AuthorizationPrincipal entity, and as you say in your question you want a one-to-many relationship.

Then, you must define your set like this:

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

This configuration should be enough for you.

EDIT

If your configuration is many-to-many, then you must have a table for the relationship between AuthoririzationPrincipal and Privileges like AuthoririzationPrincipal-Privileges

And ypur mapping must be like this:

In AuthorizationPrincipal:

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

And in Privileges:

<set name="authorizationPrincipals" inverse="true" table="AuthoririzationPrincipal-Privileges">
    <key column="privileges_id" />
    <many-to-many class="AuthoririzationPrincipal" column="authorization_principal_id" />
</set>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top