springboot 集成 mybatisplus时,查询碰到的问题

4 篇文章 0 订阅
3 篇文章 0 订阅

前端传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’

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值