Hibernate:映射嵌套对象-EDITED-

时间:2014-09-10 16:59:07

标签: java hibernate hibernate-mapping

例如,我有以下表格:

USER:

| USERID | USERNAME | USERTYPEID |

USERTYPE:

| USERTYPEID | USERTYPENAME |

很明显,USERTYPEID是用户用来引用usertype的外键。 JAVA实现如下:

我有一个User类和一个UserType类,如下所示:

public class User {
    private int id;
    private UserType ut;
    ....
}

public class UserType {
    ...
}

在User.hbm.xml中:

<hibernate-mapping>
   <class name="com.pretech.User" table="User">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="UserID">
         <generator class="native"/>
      </id>
   </class>
</hibernate-mapping>

所以我的问题如下:

1)我应该在这里映射UserType并将UserType指示为外键?

2)如果用户包含UserType的列表(可能在概念上不是真的,但只是想用作示例),例如:

public class User {
    private int id;
    private List<UserType> uts;
}

我对hibernate映射做了什么?

修改 添加了关于外键的解释。

2 个答案:

答案 0 :(得分:1)

您的示例中有很多网络示例,您还可以查看hibernate documentation

例如,如果您希望User实体具有一组UserType's,那么您可以使用one-to-many关系,映射文件将是:

<class name="User">
    <id name="id" column="id">
        <generator class="native"/>
    </id>
    <set name="uts">
        <key column="userId" 
            not-null="true"/>
        <one-to-many class="UserType"/>
    </set>
</class>

<class name="UserType">
    <id name="id" column="id">
        <generator class="native"/>
    </id>
</class>

here是使用注释和List而不是Set的文档中的另一个示例:

答案 1 :(得分:0)

它应该是OneToOne或OneToMany,具体取决于UserType是单个引用还是多个(集合列表)。 在Google上搜索,您将获得大量基于xml和基于注释的教程

相关问题