记录一个bug:com.mysql.cj.exceptions.DataConversionException: Unsupported conversion

471 阅读1分钟

使用mybatis-plus查询数据库的时候报错:com.mysql.cj.exceptions.DataConversionException: Unsupported conversion from LONG to java.sql.Timestamp

  • 一开始以为是数据类型不匹配,于是看了好几遍代码,花费了2个小时都找不到原因。最后在实体类中找到了锅。

经过各种找资料排查,发现原来是实体类的锅。实体类如下:

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_user")
public class User extends Model<User>{

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    private Long id;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 创建时间
     */
    @TableField(value = "create_time")
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField(value = "update_time")
    private Date updateTime;

    public User(String username, String password, int age, LocalDateTime createTime, Date updateTime) {

        this.username = username;
        this.password = password;
        this.age = age;
        this.createTime = createTime;
        this.updateTime = updateTime;
    }

    @Override
    protected Serializable pkVal() {
        return this.id;
    }

}

问题就出现在构造方法这里,当我们定义了一个有参构造函数,系统会自动把我们的无参构造函数去掉,就会导致new对象的时候,无法通过无参构造方法生成对象。

  • 解决方法:增加无参构造方法
public User() {
}
  • 或者在实体类添加注解 @NoArgsConstructor即可解决