在SpringMVC和Mybatis中使用LocalDataTi

作者: 编码工匠 | 来源:发表于2018-04-24 13:35 被阅读7次

需要在maven中添加依赖:

        <!--LocalDateTime-->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-typehandlers-jsr310</artifactId>
            <version>1.0.2</version>
        </dependency>

添加配置文件

  springboot或spring自定义jackson的MapperObject对象,spring也可以通过xml配置的方式加入jackson配置。

@Configuration
public class JacksonConfig {
    @Bean(name = "mapperObject")
    public ObjectMapper getObjectMapper() {
        ObjectMapper om = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        om.registerModule(javaTimeModule);
        return om;
    }
}

  SpringMVC使用@RequestBody、@ResponseBody、@RestController注解时,会使用自定义的MapperObject对象进行json到LocalDate、LocalTime、LocalDateTime对象转换。

  Mybatis通过通过mybatis-typehandlers-jsr310来把LocalDate、LocalTime、LocalDateTime映射到数据库的date、timestamp、datetime等字段。

  如果SpringMVC接受的不是json参数,则要使用@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)注解来转换LocalDateTime

    @PostMapping("/test1")
    public void test1(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime localDateTime ) {
    }
    @PostMapping("/test2")
    public void test2(@RequestParam @DateTimeFormat(iso = "dd.MM.yyyy") LocalDate localDate ) {
    }

相关文章

网友评论

    本文标题:在SpringMVC和Mybatis中使用LocalDataTi

    本文链接:https://www.haomeiwen.com/subject/rsfjlftx.html