0

So far the association works fine (the User class loads the appropriate UserRoles instance when present), but when creating a new User and setting its Roles property to a new instance of UserRoles, the UserRoles object is not saved.

Here is my abridged User.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="DistrictObservations.User, DistrictObservations" table="users">
    <cache usage="read-write" region="all" />

    <id name="ID" column="id" type="int" unsaved-value="0">
      <generator class="identity" />
    </id>

    <!-- snip -->

    <one-to-one name="Roles" class="DistrictObservations.UserRoles, DistrictObservations" lazy="false" />

  </class>
</hibernate-mapping>

And here is the UserRoles mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="DistrictObservations.UserRoles, DistrictObservations" table="user_roles">
    <cache usage="read-write" region="all" />

    <id name="UserID" column="user_id" type="int" >
      <generator class="foreign">
        <param name="property">User</param>
      </generator>
    </id>

    <!-- snip -->

    <one-to-one name="User" class="DistrictObservations.User, DistrictObservations" lazy="false" constrained="true" foreign-key="FK_user_roles_users" />

  </class>
</hibernate-mapping>

Anyone got an idea how to have the UserRoles object saved with the User.ID as its primary key? I've been looking at the documentation, and to be honest, it is not particularly helpful.

4

3 回答 3

2

通常你不需要一对一的,除非你被一个不可变的遗留数据库模式困住了。大多数用户-角色映射允许用户具有多个角色,并且角色可以被任意数量的用户使用,这意味着用于多对多关联的关联表。

如果您的应用程序只需要每个用户一个角色,那么我建议将 RoleId 作为 FK 直接放在 Users 表中。

话虽如此,如果您出于某种原因坚持一对一,请确保在不会进行更新的那个(“子”实体)上使用 inverse="true"。(有关 inverse 属性的更多信息,请参阅 Hibernate 一对一文档——它应该对此进行足够的解释。)

于 2009-01-22T01:19:57.537 回答
0

我可能遗漏了一些东西,但是您需要在 User 和 UserRoles 之间建立一对一的关系吗?你不能在用户和角色之间建立一对多的关系吗?UserRoles 似乎是多余的。

于 2009-01-21T22:34:39.853 回答
0

我发现很少需要一对一的映射。我通常认为的一对一映射通常是一对多映射。两个表上的主键值相同并不常见。

从类名的外观来看,您似乎正在尝试将角色与用户相关联?在我看来,这不像是一对一的。

也就是说,看起来外国类的生成器应该做你需要的。

于 2009-01-22T00:15:21.973 回答