2

我已经研究了很长时间,但仍然无法弄清楚我的代码有什么问题。每个服务有多个配置文件,但每个配置文件只有一个服务。

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

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

在 Profile.hbm.xml 中。我加

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

这是映射它的正确方法吗?

4

1 回答 1

10

每个服务有多个配置文件,但每个配置文件只有一个服务。

然后相应地设计您的对象模型。使用 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 回答