2

I have been working on it for quite a while, but still can't figure out what's wrong with my code. Each Service has multiple profiles, but each profile only has one Service.

Service
{
Long service_id; // primary key
... getter/setter
}

Profile
{
Long profile_id; // primary key
Long service_id; // foreign key
... getter and setter
}

in Profile.hbm.xml. I add

< many-to-one name="service_id" class="com.mot.diva.dto.Service" column="SERVICE_ID" cascade="save-update">
< /many-to-one>

Is it the correct way to map it?

4

1 に答える 1

10

各サービスには複数のプロファイルがありますが、各プロファイルには 1 つのサービスしかありません。

次に、それに応じてオブジェクト モデルを設計します。ORM ツールを使用する場合、id ではなく、オブジェクト (エンティティ) とエンティティ間の関係を考える必要があります。ORM は、PK、FK、結合などを処理します。したがって、コードは次のようになります。

public class Service implements Serializable {
    private Long service_id; // primary key
    private Set<Profile> profiles = new HashSet<Profile>();

    // ... getter/setter
}

public class Profile implements Serializable {
    private Long profile_id; // primary key
    private Service service;

    // ... getter and setter
}

そしてProfile.hbm.xmlマッピングファイル:

....
<many-to-one name="service" 
             class="com.mot.diva.dto.Service"
             column="SERVICE_ID"
             cascade="save-update">
</many-to-one>
...

そしてService.hbm.xml(あなたの関連付けは双方向であるように見えるため):

...
<set name="profiles" inverse="true">
    <key column="PROFILE_ID" not-null="true"/>
    <one-to-many class="com.mot.diva.dto.Profile"/>
</set>
...
于 2010-03-23T22:04:56.600 に答える