1. Use try-with-resources to properly handle the resources used in the method.
try {
    // code...
} catch (ParseException e) {
    e.printStackTrace();
}
  1. Instead of using System.out.println() for logging, consider using a logging framework like SLF4J or Log4j.

  2. Move the logic for generating the next seven days outside the loop to avoid redundant computations.

List<String> sevenDays = RcqtUtils.getNextSevenDaysUn();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  1. Avoid unnecessary database queries inside the loop by fetching all default times for coaches beforehand.
List<DefaultTime> defaultTimes = defaultTimeService.queryDefaultTimeByCoachIDs(coachList.stream().map(Coach::getCoachId).collect(Collectors.toList()));
  1. Use a Map to store the default times for each coach for easier lookup.
Map<Long, List<DefaultTime>> defaultTimesMap = defaultTimes.stream().collect(Collectors.groupingBy(DefaultTime::getCoachId));
  1. Iterate over the coaches and retrieve their default times from the defaultTimesMap.
for (Coach coach : coachList) {
    List<DefaultTime> defaultTimes = defaultTimesMap.get(coach.getCoachId());
    // rest of the code...
}
  1. Use a Set to store the dates that need to be checked for each coach to avoid duplicates.
Set<Date> datesToCheck = new HashSet<>();
for (String s : sevenDays) {
    Date date = dateFormat.parse(s);
    datesToCheck.add(date);
}
  1. Fetch all existing update times for the coaches and dates in a single query.
List<UpdateTime> existingUpdateTimes = updateTimeService.queryUpdateTimeByDates(coachList.stream().map(Coach::getCoachId).collect(Collectors.toList()), datesToCheck);
  1. Use a Set to store the dates for which update times have already been generated.
Set<Date> generatedDates = new HashSet<>();
for (UpdateTime updateTime : existingUpdateTimes) {
    generatedDates.add(updateTime.getCourseDate());
}
  1. Generate new update times for the remaining dates.
List<UpdateTime> newUpdateTimes = new ArrayList<>();
for (Coach coach : coachList) {
    List<DefaultTime> defaultTimes = defaultTimesMap.get(coach.getCoachId());
    for (String s : sevenDays) {
        Date date = dateFormat.parse(s);
        if (!generatedDates.contains(date)) {
            // generate new update times
            // rest of the code...
        }
    }
}
  1. Batch insert the new update times using saveBatch().
boolean success = updateTimeService.saveBatch(newUpdateTimes);
``
Scheduledcron = 0 0 23 每天23点执行 public void myTask 在这里执行你的数据库操作代码 Systemoutprintln定时任务执行; 1查询所有教练 ListCoach coachList = coachServicequeryAllCoaches; ListUpdateT

原文地址: http://www.cveoy.top/t/topic/hNw5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录