若依删除关联数据,外键约束异常处理
报错如下:
- 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))
复制代码
解决方法:增加异常类代码
- /**
- * 数据完整性约束异常
- */
- @ExceptionHandler(DataIntegrityViolationException.class)
- public AjaxResult handleDataIntegrityViolationException(DataIntegrityViolationException e)
- {
- log.error(e.getMessage(), e);
- if (e.getCause() instanceof SQLIntegrityConstraintViolationException sqlException) {
- if (sqlException.getMessage().contains("foreign key constraint")) {
- return AjaxResult.error("无法删除该区域,因为存在关联的数据,请先删除关联数据");
- }
- }
- return AjaxResult.error("数据操作违反完整性约束,请联系管理员");
- }
复制代码 如图所示:
|
|