今天写业务代码有这么一个场景,就是在数据库表中插入一条数据,并且这个表中只有这么一条。
因为是用的Mybatis-Plus所以直接用它来实现业务功能,起初是把要插入的数据放到mybatis-plus中,代码如下
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(ProjectCompany::getProjectId,projectId).eq(ProjectCompany::getCompanyId,user.getCompanyId()).eq(ProjectCompany::getIsDelete,"0"); List projectCompanies = projectCompanyMapper.selectList(wrapper);
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();wrapper.eq(ProjectCompany::getProjectId,projectId).eq(ProjectCompany::getCompanyId,user.getCompanyId()).eq(ProjectCompany::getIsDelete,"0");List projectCompanies = projectCompanyMapper.selectList(wrapper);
就是把要插入的数据先在表中查出来是否存在,查出来的结果放到List集合中,但是在遍历时始终想不到合适的思路,起初是这样写的
for (ProjectCompany projectCompany1 : projectCompanies) { if (!(projectCompany1.getCompanyId().equals(projectCompany.getCompanyId())) && !(projectCompany1.getProjectId().equals(projectCompany.getProjectId()))){ projectCompanyMapper.insert(projectCompany); break; } }
for (ProjectCompany projectCompany1 : projectCompanies) { if (!(projectCompany1.getCompanyId().equals(projectCompany.getCompanyId())) && !(projectCompany1.getProjectId().equals(projectCompany.getProjectId()))){ projectCompanyMapper.insert(projectCompany); break; }}
因为不知道 if (!(projectCompany1.getCompanyId().equals(projectCompany.getCompanyId())) && !(projectCompany1.getProjectId().equals(projectCompany.getProjectId()))) (大家对这个有什么解决办法,欢迎留言给c主提供一下) 该怎么判断。试来试去始终不行,后面就换了一种思路,不查所有数据了,我只在表中查一条
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(ProjectCompany::getProjectId,projectCompany.getProjectId()).eq(ProjectCompany::getCompanyId,projectCompany.getCompanyId()).eq(ProjectCompany::getIsDelete,"0");ProjectCompany projectCompany1 = projectCompanyMapper.selectOne(wrapper); if (projectCompany1 ==null){ projectCompanyMapper.insert(projectCompany); }
LambdaQueryWrapper
wrapper.eq(ProjectCompany::getProjectId,projectCompany.getProjectId()).eq(ProjectCompany::getCompanyId,projectCompany.getCompanyId()).eq(ProjectCompany::getIsDelete,"0");
ProjectCompany projectCompany1 = projectCompanyMapper.selectOne(wrapper);
if (projectCompany1 ==null){
projectCompanyMapper.insert(projectCompany);
}
就是我还用之前的查询条件,只不过这次查询我查一条数据projectCompanyMapper.selectOne(wrapper);
然后判断这个结果是不是空的,如果是空的则说明数据库中没有该数据,则可以进行插入。相反如果不为空,则说明表中有数据。
但是上面代码还会出现一个异常,就是 projectCompanyMapper.selectOne(wrapper); 可能会查出多条数据,所以我们还要对该异常进行一个处理
try { ProjectCompany projectCompany1 = projectCompanyMapper.selectOne(wrapper); if (projectCompany1 ==null){ projectCompanyMapper.insert(projectCompany); } }catch (Exception e){ throw new BaseException("数据有误,待周一回来调试,原因是ProjectCompany表中"); }
try { ProjectCompany projectCompany1 = projectCompanyMapper.selectOne(wrapper); if (projectCompany1 ==null){ projectCompanyMapper.insert(projectCompany); }}catch (Exception e){ throw new BaseException("数据有误,待周一回来调试,原因是ProjectCompany表中");}
因为是周五,要着急下班,所以异常信息自己定义的一个,今天就说这么多吧。
喜欢的话可以给个赞哦
来源地址:https://blog.csdn.net/xiaoheihai666/article/details/127695556