hibernate 多对多删除解决方案

hibernate多对多当中,我们常常希望只删除一方已及对应的关系,但不想删除另一方,怎么样达到呢? (这里只提删除)

表user和表role多对多,中间表user_role(userId,roleId),user是主控方,role是从方,

在spring+hibernate的环境下,使用的是Annotation配置

 

User.java

@ManyToMany(cascade = {CascadeType.MERGE,CascadeType.PERSIST}, fetch = FetchType.EAGER)
@JoinTable(name = "user_role",

joinColumns = { @JoinColumn(name = "userId",referencedColumnName="userId") },

inverseJoinColumns = { @JoinColumn(name = "roleId",referencedColumnName="roleId") })
 public Set<Role> getRoles() {
  return this.roles;
 }

 

Role.java

@ManyToMany(cascade = {CascadeType.MERGE,CascadeType.PERSIST}, fetch = FetchType.EAGER,

 mappedBy = "roles")
 public Set<User> getUsers() {
  return this.users;
 }

 

测试:主控方User删除,user会被删除,user_role的中的关系也会被删除了,但对应的role不会被删除

@Test
 public void testDelete() {
  User user = userDao.findById(8);
  userDao.delete(user);
 }

测试:从方Role删除,如果user_role里面没有对应的roleId,role可以删除,user不会被删除

@Test
 public void testDelete() {
  Role role = roleDao.findById(26);
  roleDao.delete(role); 

}

测试:从方Role删除,如果user_role里面有对应的roleId和别的userId关联,role不能被删除

@Test
 public void testDelete() {
  Role role = roleDao.findById(26);
  roleDao.delete(role); 

}

会报错:org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update


Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (`hrms`.`user_role`, CONSTRAINT `roleId` FOREIGN KEY (`roleId`) REFERENCES `role` (`roleId`) ON DELETE NO ACTION ON UPDATE NO ACTION)

解决方案:在数据库里更改user_role表结构,就是添加约束,就添加roleId的删除时进行级联操作

ALTER TABLE `hrms`.`user_role`

  ADD CONSTRAINT `roleId`

  FOREIGN KEY (`roleId` )

  REFERENCES `hrms`.`role` (`roleId` )

  ON DELETE CASCADE;

 

测试:从方Role删除,如果user_role里面有对应的roleId,现在role可以删除,user_role里面对应的关系也会被删除,但对应的user不会被删除,达到我们想要的效果

@Test
 public void testDelete() {
  Role role = roleDao.findById(26);
  roleDao.delete(role); 

}

 

你可能感兴趣的:(exception,Hibernate,jdbc,user,测试,delete)