springboot中日期类型的数据如何正确插入到数据库中

项目场景:

在前端页面中对数据库中的实体类进行修改

问题描述:

可能是格式的原因,点击修改按钮后报如下错误,大概意思就是类型不匹配,错误代码如下

Field error in object 'employee' on field 'employeeBirthday': rejected value [2020-10-23]; codes [typeMismatch.employee.employeeBirthday,typeMismatch.employeeBirthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.employeeBirthday,employeeBirthday]; arguments []; default message [employeeBirthday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'employeeBirthday'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-10-23'; nested exception is java.lang.IllegalArgumentException]]

原因分析:

查看日志可以看到是传入的日期数据和数据库中的日期类型不对应

解决方案:

  1. 前端代码
<div class="input-group date">
                                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        <input type="text" class="form-control" name="employeeInductionTime"
                                               th:value="${#dates.format(employee.getEmployeeInductionTime(),'yyyy-MM-dd')}"
                                               style="width:120px;height:35px;">
                                    </div>

就是在你的input框中加入这行代码,固定日期格式,主要是画横线的部分,剩下部分是你自己输入的日期内容
在这里插入图片描述

  1. 后端代码
 /**
     * 出生日期
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date employeeBirthday;
    /**
     * 入职日期
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date employeeInductionTime;

就是在有关日期的实体类上加上 @DateTimeFormat(pattern = “yyyy-MM-dd”),来固定日期的格式,致此,bug就解决啦。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值