我创建了一个 UserObject 和 RoleObject 来代表我的应用程序中的用户。我正在尝试使用 hibernate 来进行 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]
我的数据库定义如下:
用户表、权限表和权限表。权限表是用户和权限的联接。
我的 UserObjec 的 hibernate 映射如下:
...
<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>
我需要如何更改映射或对象结构才能保留新用户?
最佳答案
您正在“set”元素内定义两种不同的关系。您可能想要的只是多对多元素。
如果这仍然不起作用,请尝试保存 UserRole 本身,看看是否可以自行保留它。如果可以,那么在尝试保留 User 时将抛出 ConstraintViolationException。
最后一个提示,您可能不想在“角色”集上级联保存/更新。您的 UserRoles 很可能已经在数据库中,并且在创建用户时简单地附加到用户。
关于java - 使用 Hibernate 保留用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/322243/