首先Java 8的日期类型LocalDate,LocalDateTime,LocalTime在Mybatis中并没有映射关系,为此mybatis推出了一个补丁。
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-typehandlers-jsr310</artifactId> <version>1.0.1</version> </dependency>
如果是mybatis-plus的话,依赖版本如下
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.22</version> </dependency>
代码中带时间格式的字段设置标签如下(使用jackson)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private LocalDateTime time;
在Controller的方法参数里,如果使用了
@RequestParam("date") LocalDate date
当我们传递参数时,会被当成字符串,抛出异常。需要添加一个Controller增强器
@ControllerAdvice public class GlobalJava8DateHandler { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class,new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(DateUtils.parse(text,DateUtils.pattern4)); } }); binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd"))); } }); binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); } }); binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss"))); } }); } }
@InitBinder,用于request中自定义参数解析方式进行注册,从而达到自定义指定格式参数的目的。