栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

前端传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 {
    @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中查询语句处理

	
       and DATE_FORMAT(mothFieled,'%Y-%m') =
        substring_index(#{data.mothFieled},'-',2)
                

解释: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’

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759533.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号