一、问题描述
在用SpringMVC整合mybatis的时候,在controller中调用service进行保存数据的操作,遇到了Failed to convert from type java.lang.String to type java.util.Date for value………这个错误,然后发现数据库字段在Entity中的类型是Date的,然后表单传过来的数据时String类型的,这时就会出现这样的问题,类型转换错误!
二、解决办法
要加一个@InitBinder,查了一下资料 https://url.cn/50jfk0F,貌似是用于初始化数据的时候,进行数据类型转换,把String类型转为Date类型,这样就不会报错了。
- @InitBinder
- public void initBinder(WebDataBinder binder) {
- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- dateFormat.setLenient(true);
- binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
- }
这个要加在相关的Controller里面就可以了