同时对数据库进行更新,添加与删除操作

1.测试接口方法如下

private void updateCourseList(String classId, JSONObject request, JSONObject user) {
  JSONArray courseList = request.optJSONArray("courseList");
  String insertSql = "insert into cekasp_train_course(id, classId, name, teacherName, status, createUser, createDate) values (?, ?, ?, ?, 0, ?, now())";
  String updateSql = "update cekasp_train_course set name = ?, teacherName = ?, updateUser = ?, updateDate = now() where id = ? and classId = ? and status >= ?";
  List courseIdList = new ArrayList<>();
  for (int i = 0, len = courseList.length(); i < len; i++) {
  JSONObject course = courseList.optJSONObject(i);
  String id = course.optString("id", null);
  String name = course.optString("name");
  String teacherName = course.optString("teacherName");
  if (ValidateUtil.isNull(id)) { // 如果没有id,就添加到数据库
  id = String.valueOf(dataService.getAutoId("cekasp_train_course"));
  dataService.getJdbcTemplate().update(insertSql, id, classId, name, teacherName, user.optString("id"));
  log.info("add course, name is {}, id is {}", name, id);
  } else { // 如果有id,就更新
  dataService.getJdbcTemplate().update(updateSql, name, teacherName, user.optString("id"), id, classId, DataStatusEnum.NORMAL.getValue());
  log.info("update course, new name is {}, id is {}", name, id);
}
  courseIdList.add(id);
}
  NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataService.getJdbcTemplate());
  Map paramMap = new HashMap<>();
  paramMap.put("status", DataStatusEnum.DELETED.getValue());
  paramMap.put("ids", courseIdList);
  paramMap.put("classId", classId);
  namedParameterJdbcTemplate.update("update cekasp_train_course set status = (:status) where classId = (:classId) and id not in (:ids)", paramMap);
}

转载于:https://www.cnblogs.com/xiaolin-peter/p/7196080.html

你可能感兴趣的:(同时对数据库进行更新,添加与删除操作)