2010-03-23 195 views
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> 

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

回答

9

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

然后相应地设计你的对象模型。当使用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> 
... 
+0

感谢您的回答。它完美的作品。有时候我对ibatis和hibernate感到困惑。 〜 – Lily

+0

@Lily不客气。 iBATIS更多的是一个数据映射器(更低层次,更接近数据库),而不是真正的ORM。使用ORM,您必须考虑对象,而不是表格。 –