前端传2022-03,spring mvc接收问题
dto中对应的字段类型为java8 中的LocalDate
通过get请求时,接收该字段会有以下异常:
default message
[Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'mothFieled';
nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat
@io.swagger.annotations.ApiModelProperty java.time.LocalDate] for value '2022-03'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-03]]]
解决办法:定义转换器
@Component
public class MonthConverter implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String source) {
try {
if(StringUtils.isNotEmpty(source)){
// 方法一 返回2022-03-01
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
// 2022-03-01
return LocalDate.parse(source, fmt);
// 方法二 返回2022-03-31
// DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
// YearMonth ym = YearMonth.parse(source, fmt);
// 2022-03-31
// return ym.atEndOfMonth();
}
// 方法三不能实现,只能转换pattern = “yyyy-MM-dd” 或其他
// return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
根据上面的转换器,会将实体中的字段自动转换为:mothFieled = 2022-03-31
mybatis / mybatisplus xml中查询语句处理
<where>
<if test="data.mothFieled!= null">
and DATE_FORMAT(mothFieled,'%Y-%m') =
substring_index(#{data.mothFieled},'-',2)
</if>
</where>
解释:LocalDate为对象类型,在if中只能判断是否为null ,如果判断字符串为空(and data.mothFieled!= ‘’),则会出现以下异常:
java.lang.IllegalArgumentException: invalid comparison:
java.time.LocalDate and java.lang.String
at org.apache.ibatis.ognl.OgnlOps.compareWithConversion(OgnlOps.java:98) ~[mybatis-3.5.6.jar:3.5.6]
DATE_FORMAT: 将数据库字段转换为对应格式的值;
substring_index: 将传输的值通过指定字符截取相应的长度;
最后sql为: a.mothFieled = ‘2022-03’