【问题标题】:Persisting Users using Hibernate使用 Hibernate 持久化用户
【发布时间】:2010-09-24 05:57:27
【问题描述】:

我创建了一个 UserObject 和 RoleObject 来代表我的应用程序中的用户。我正在尝试将休眠用于 CRUD 而不是原始 JDBC。我已成功从数据库中检索到信息,但无法创建新用户。我收到以下错误。

org.springframework.web.util.NestedServletException: Request processing failed; nested
exception is org.springframework.dao.DataIntegrityViolationException: could not insert: 
[com.dc.data.UserRole]; nested exception is 
org.hibernate.exception.ConstraintViolationException: could not insert: 
[com.dc.data.UserRole]

我的数据库定义如下:

用户表、权限表和权限表。 Authorities 表是用户和权限的连接。

我的 UserObjec 的休眠映射如下:

  ...
  <set name="roles" table="authorities" cascade="save-update"  lazy="false" >
            <key column="userId" />
            <one-to-many class="com.dc.data.UserRole"/>
            <many-to-many  class="com.dc.data.UserRole" column="authId" />
        </set>
    </class>
   ...

UserRole 映射如下:

<class name="com.dc.data.UserRole" table="authority">
    <id name="id" column="authId">
        <generator class="native" />
    </id>
    <property name="roleName">
        <column name="authority" length="60" not-null="true" />
    </property>
</class>

我需要如何更改我的映射或对象结构才能保留新用户?

【问题讨论】:

    标签: java mysql hibernate


    【解决方案1】:

    您在“set”元素中定义了两种不同的关系。您可能想要的只是多对多元素。

    如果这仍然不起作用,请尝试保存 UserRole 本身,看看您是否可以自行保留它。如果可以,那么在尝试持久化用户时会抛出 ConstraintViolationException。

    最后一个提示,您可能不想在“角色”集上级联保存/更新。您的 UserRoles 很可能已经在数据库中,并且在创建时简单地附加到用户。

    【讨论】:

    • 如果您能将我的答案标记为正确答案,那就太好了。 :)
    【解决方案2】:

    UserRole 上的约束冲突可能是尝试插入具有重复键的行的原因。也许可以尝试使用其他类型的生成器,例如“序列”。

    【讨论】:

      猜你喜欢
      • 2011-05-12
      • 2013-11-12
      • 2014-12-14
      • 2010-11-24
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多