在多对多或其他关联映射中,如果只是希望更新关联关系,而不进行级联保存。如下,PrivilegeGroup和SystemPrivilege是多对多双向关联关系,通过new构造一个数据库中已有的SystemPrivilege然后和PrivilegeGroup设置关系,进行保存:
PrivilegeGroup group = new PrivilegeGroup(); group.setName(name); SystemPrivilege systemPrivilege = new SystemPrivilege(id); group.getPrivileges().add(systemPrivilege); privilegeGroupService.save(group);
接着提示如下错误:
Caused by: java.sql.BatchUpdateException: Duplicate entry 'department-view' for key 1
原因是,虽然SystemPrivilege在数据库中已有,但是由于这里是new出来的对象,属于transient状态,由于设置了:
所以进行级联保存,导致提示主键冲突:
Duplicate entry 'department-view' for key 1
如果希望只是设置关系而不更新,则可以在SystemPrivilege的主键中设置unsaved-value="none"属性:
除了文章中有特别说明,均为IT宅原创文章,转载请以链接形式注明出处。
本文链接: http://www.itzhai.com/hibernate-is-mapping-to-create-the-database-objects-that-exist-in-association-does-not-set-the-cascade-method-of-preservation.html
本文链接: http://www.itzhai.com/hibernate-is-mapping-to-create-the-database-objects-that-exist-in-association-does-not-set-the-cascade-method-of-preservation.html