hibernate外键映射多对一

Lil*_*ily 2 orm hibernate foreign-keys map many-to-one

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

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

Profile
{
Long profile_id; // primary key
Long service_id; // foreign key
... getter and setter
}
Run Code Online (Sandbox Code Playgroud)

在Profile.hbm.xml中.我加

< many-to-one name="service_id" class="com.mot.diva.dto.Service" column="SERVICE_ID" cascade="save-update">
< /many-to-one>
Run Code Online (Sandbox Code Playgroud)

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

Pas*_*ent 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
}
Run Code Online (Sandbox Code Playgroud)

Profile.hbm.xml映射文件:

....
<many-to-one name="service" 
             class="com.mot.diva.dto.Service"
             column="SERVICE_ID"
             cascade="save-update">
</many-to-one>
...
Run Code Online (Sandbox Code Playgroud)

而且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>
...
Run Code Online (Sandbox Code Playgroud)