/** * 日期过滤 */ private void dateFilter(String dateField, LambdaQueryWrapper<TmpOrderAuxiliaryPlanEntity> wrapper, String fieldName) { List<String> dateArray; String sqlDateField = DataConversionUtil.humpToUnderline(fieldName); dateArray = Arrays.stream(dateField.split(Constant.SEP)).collect(Collectors.toList()); StringBuilder sql = new StringBuilder(); for (int i = 0; i < dateArray.size(); i++) { sql.append(Constant.SINGLE_QUOTE).append(dateArray.get(i)).append(Constant.SINGLE_QUOTE).append(Constant.SEP); } String stringSql = sql.deleteCharAt(sql.length() - 1).toString(); //查询日期满足条件且为空的值 //wrapper.apply("DATE_FORMAT(" + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ") or " + sqlDateField + " is null"); if (stringSql.contains(Constant.NULL)) { //wrapper.apply("" + sqlDateField + " is null"); if (sqlDateField.equals(DataConversionUtil.humpToUnderline(Constant.PLANNED_DELIVERY_DATE))) { wrapper.apply("DATE_FORMAT(" + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ")").or().isNull(TmpOrderAuxiliaryPlanEntity::getPlannedDeliveryDate); //wrapper.apply("DATE_FORMAT(" + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ")"); } } else { wrapper.apply("DATE_FORMAT(" + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ")"); } }
注意事项 :
查询为空不要这样写:
wrapper.apply("DATE_FORMAT(" + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ") or " + sqlDateField + " is null"); 会影响其他wrapper拼接的sql
正确写法:
wrapper.apply("DATE_FORMAT("( + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ") or " + sqlDateField + " is null)");
或:
wrapper.apply("DATE_FORMAT(" + sqlDateField + ",'%Y-%m-%d') in (" + stringSql + ")").or().isNull(TmpOrderAuxiliaryPlanEntity::getPlannedDeliveryDate);
说明:
wrapper.apply():sql自由拼接方法 可能会有sql注入风险 也可用于MySql 可用于.last()方法之前
LambdaQueryWrapper:可以直接从实体中获取值,避免硬编码
DATE_FORMAT() sql函数 用于日期格式转换
Constant.SEP == “,” (逗号)
Constant.SINGLE_QUOTE == “'” (单引号)、
DataConversionUtil.humpToUnderline() :驼峰转下划线方法