新建和修改都要做校验。根据两个字段来判断。如果查询到有数据,则不允许插入或者修改。
如果查询到没有。则允许插入或者修改。(数据库字段没有做任何限制,一个是varchar类型一个是number类型)
直接SQL语句使用EXISTS关键词啊,例如:SELECT * FROM A WHERE EXISTS (SELECT * FROM B WHERE A.ID=B.ID)
public Map insertSmsAlerts(Map SmsAlertsInfo){
Map resultMap = new HashMap();
try {
int result = 0;
ClientSmsAlerts clientAppSmsAlerts = new ClientSmsAlerts();
clientAppSmsAlerts.setStatus(SmsAlertsInfo.get("status") == null ? "" : SmsAlertsInfo.get("status").toString());
clientAppSmsAlerts.setMonthOrWeek(SmsAlertsInfo.get("monthOrWeek") == null ? "" :SmsAlertsInfo.get("monthOrWeek").toString());
clientAppSmsAlerts.setRemindMonth(SmsAlertsInfo.get("remindMonth") == null ? "" :SmsAlertsInfo.get("remindMonth").toString());
clientAppSmsAlerts.setRemindDay(SmsAlertsInfo.get("remindDay") == null ? "" :SmsAlertsInfo.get("remindDay").toString());
clientAppSmsAlerts.setWeek(SmsAlertsInfo.get("week") == null ? "" :SmsAlertsInfo.get("week").toString());
clientAppSmsAlerts.setRemindTime(SmsAlertsInfo.get("remindTime") == null ? "" :SmsAlertsInfo.get("remindTime").toString());
clientAppSmsAlerts.setPhoneNum(SmsAlertsInfo.get("phoneNum") == null ? "" :SmsAlertsInfo.get("phoneNum").toString());
// 首先进行条件查询
ClientSmsAlerts AppSmsAlerts = clientSmsAlertsMapper.getClientAppSmsAlerts(clientAppSmsAlerts);
//是否存在此用户
if( null == AppSmsAlerts){
//添加
result = clientSmsAlertsMapper.insertClientAppSmsAlerts(clientAppSmsAlerts);
}else{
//修改
result = clientSmsAlertsMapper.updateClientAppSmsAlerts(clientAppSmsAlerts);
}
resultMap.put("success", result >0? true:false);
resultMap.put("msg",result>0?"成功":"失败");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
resultMap.put("success", false);
resultMap.put("msg","失败,因为:"+e.getMessage());
}
return resultMap;
}
如果数据库没有做约束,那就只能先查询一下看看是否存在,然后再判断是否插入。但这种效率比较低。
建议2种方案:
1、如果你的数据库不是postgresql的话,我建议你还是对数据库表做约束,然后直接插入,只要异常就说明存在然后你catch,
如果没有就正常插入就行了。
2、使用存储过程进行添加数据。这个不用对表做约束,你自己写一个存储过程就行了。
先select count(*) from 表名 where varchar = **** and number = ****
然后在你的代码中进行判断
if(count >= 1){
//有记录存在,不允许添加
报错抛出异常
}else{
//做新增操作
}