java mybatis mysql传递LocalDateTime统一格式问题

当我们直接想 mysql 传递 LocalDateTime 进行查询时,需要 mysql-connector 的版本符合一定的条件,如我上一篇java mybatis mysql使用LocalDateTime查询问题所示。

前端传后端:

当需要前端传递如"yyyy-MM-ddTHH:mm:ss"的时间格式时,会发生Bad Request

Failed to convert value of type java.lang.String to required type java.time.LocalDate

这是因为前端传给我们的是字符串,参考文章,根据Failed to convert value of type ‘java.lang.String’ to required type ‘java.time.LocalDate’ 这条信息来看,程序不能将一个String类型的值转换成LocalDate类型(前端传过来的是String类型,程序会对这些数据进行相应的convert,当匹配不到类型时,就会抛ConversionFailedException异常)。那么就按照提示,补充相应的Converter就好了。

一、LocalDateTimeConverter

我们自定义的Converter需要实现org.springframework.core.convert.converter.Converter 接口,这种方式是针对全局生效的,如果只是针对某个接口,可以使用 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 这样的方式。

字符串转换成LocalDateTime
public class String2LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    @Override
    public LocalDateTime convert(String s) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        return LocalDateTime.parse(s, fmt);
    }
}
二、注册Converter

这里我们选择通过WebMvcConfigurationSupport addFormatters(FormatterRegistry registry)方法将自定义的Converter注册到容器里面去

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2LocalDateTimeConverter());
    }

我们打开swagger,然而发生异常:

No mapping for GET /swagger-ui.html

参考文章,遇到这种情况请先查找,最近是否添加继承了WebMvcConfigurationSupport的类
如果继承了WebMvcConfigurationSupport,则在配置文件在中配置的相关内容会失效,需要重新指定静态资源

import com.fii.amms.utils.String2LocalDateTimeConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
class WebMvcConfig extends WebMvcConfigurationSupport {
   /**
     * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

因此最终添加的代码如下:
LocalDateTimeConverter部分:

public class String2LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    @Override
    public LocalDateTime convert(String s) {
    //注意下面T要加''
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        return LocalDateTime.parse(s, fmt);
    }
}

添加注册容器及重新指定静态资源:

import com.utils.String2LocalDateTimeConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2LocalDateTimeConverter());
    }
   /**
     * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
                
        // 如果使用SpringBoot集成swagger-bootstrap-ui后,无法访问doc.html界面
        // 则需要添加如下:
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        super.addResourceHandlers(registry);
    }
}

后端传前端

后端传给前端的格式也不是 “yyyy-MM-dd’T’HH:mm:ss” 的格式,而是类似数组格式:
[yyyy,MM,dd,HH,mm,ss]
感觉不太统一

 注解@JsonFormat主要是后台到前台的时间格式的转换
 注解@DataFormAT主要是前后到后台的时间格式的转换

因此通过在传给前端的实体类上加注解: @JsonFormat(pattern = “yyyy-MM-dd’T’HH:mm:ss”) 即可

Excel导入导出

需要指定LocalDateTimeConverter,如下所示,并在需要导出Excel的实体类LocalDateTime上添加Converter的注解:

    @ExcelProperty(value = "创建时间", converter = LocalDateTimeConverter.class)
    private LocalDateTime createTime;
public class LocalDateTimeConverter  implements Converter<LocalDateTime> {
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Override
    public Class supportJavaTypeKey() {
        return null;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DEFAULT_PATTERN);
        return LocalDateTime.parse(cellData.getStringValue(), dateTimeFormatter);
    }

    @Override
    public CellData convertToExcelData(LocalDateTime localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData<>(dateTimeFormatter.format(localDateTime));
    }
}

参考文章:
Failed to convert value of type java.lang.String to required type java.time.LocalDate
No mapping for GET /swagger-ui.html
@JsonFormat与@DateTimeFormat注解的使用
【转】集成 swagger-bootstrap-ui后访问 doc.html页面404
EasyExcel导入excel中时间格式到LocalDateTime字段转换器Converter

Java中,MyBatis是一种流行的持久化框架,它提供了一种简单且灵活的方式来进行数据库操作。MySQL是一种常用的关系型数据库管理系统,它支持事务处理。 事务是一组互相关联的操作,它们被视为一个单独的工作单元。事务具有以下四个特性,通常称为ACID特性: 1. 原子性(Atomicity):事务中的所有操作要么全部成功执行,要么全部回滚。如果出现任何错误或异常,事务会回滚到初始状态,之前的操作将会回滚。 2. 一致性(Consistency):事务开始和结束时,数据库应该保持一致状态。这意味着数据在事务执行之前和之后应该满足一定的约束和完整性规则。 3. 隔离性(Isolation):事务之间应该是相互隔离的,一个事务的操作不会影响其他事务。这样可以确保事务在并发环境下保持数据的一致性。 4. 持久性(Durability):一旦事务提交成功,对数据所做的更改应该永久保存在数据库中,即使发生系统故障或电源故障。 在Java中使用MyBatisMySQL进行事务回滚,我们可以采取以下步骤: 1. 首先,我们需要在MyBatis的配置文件中启用事务管理器。可以使用JDBC的事务管理器,也可以使用Spring事务管理器等。 2. 在需要进行事务管理的方法上使用注解或XML配置事务。注解方式可以使用`@Transactional`注解,XML配置方式可以使用`<transaction>`标签。 3. 在事务管理的方法中,我们可以使用`try-catch`块来捕获可能发生的异常,如果出现异常,则可以调用`TransactionManager`的`rollback`方法来回滚事务。 4. 如果所有操作都执行成功,我们可以调用`TransactionManager`的`commit`方法来提交事务,将更改持久化保存到数据库中。 总之,Java中使用MyBatisMySQL进行事务管理和回滚是非常简单和灵活的。通过合理地配置和使用事务管理器,我们可以确保数据库操作的一致性和可靠性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值