若依删除关联数据,外键约束异常处理

[复制链接]
admin 发表于 6 天前 | 显示全部楼层 |阅读模式
若依删除关联数据,外键约束异常处理


报错如下:
  1. Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (dkd1.tb_emp, CONSTRAINT tb_emp_ibfk_2 FOREIGN KEY (region_id) REFERENCES tb_region (id)) ### The error may exist in file [F:\home\jinhei-parent\jinhei-manage\target\classes\mapper\manage\RegionMapper.xml] ### The error may involve com.jinhei.manage.mapper.RegionMapper.deleteRegionByIds-Inline ### The error occurred while setting parameters ### SQL: delete from tb_region where id in ( ? ) ### Cause: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (dkd1.tb_emp, CONSTRAINT tb_emp_ibfk_2 FOREIGN KEY (region_id) REFERENCES tb_region (id)) ; Cannot delete or update a parent row: a foreign key constraint fails (dkd1.tb_emp, CONSTRAINT tb_emp_ibfk_2 FOREIGN KEY (region_id) REFERENCES tb_region (id))
复制代码


解决方法:增加异常类代码
  1. /**
  2.      * 数据完整性约束异常
  3.      */
  4.     @ExceptionHandler(DataIntegrityViolationException.class)
  5.     public AjaxResult handleDataIntegrityViolationException(DataIntegrityViolationException e)
  6.     {
  7.         log.error(e.getMessage(), e);
  8.         if (e.getCause() instanceof SQLIntegrityConstraintViolationException sqlException) {
  9.             if (sqlException.getMessage().contains("foreign key constraint")) {
  10.                 return AjaxResult.error("无法删除该区域,因为存在关联的数据,请先删除关联数据");
  11.             }
  12.         }
  13.         return AjaxResult.error("数据操作违反完整性约束,请联系管理员");
  14.     }
复制代码
如图所示:
1.jpg

网站建设,公众号小程序开发,多商户单商户小程序制作,高端系统定制开发,App软件开发联系我们【手机/微信:17817817816
微信扫码

网站建设,公众号小程序开发,商城小程序,系统定制开发,App软件开发等

粤ICP备2024252464号

在本版发帖
微信扫码
QQ客服返回顶部
快速回复 返回顶部 返回列表