mybatis使用Java8的日期LocalDate与LocalDateTime的实例

这篇文章主要给大家介绍了关于mybatis如何使用Java8的日期LocalDate和LocalDateTime的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

前言

相信大家应该都知道,在实体Entity里面,可以使用java.sql.Date、java.sql.Timestamp、java.util.Date来映射到数据库的date、timestamp、datetime等字段

但是,java.sql.Date、java.sql.Timestamp、java.util.Date这些类都不好用,很多方法都过时了。

Java8里面新出来了一些API,LocalDate、LocalTime、LocalDateTime 非常好用

默认的情况下,在mybatis里面不支持java8的时间、日期。直接使用,会报如下错误

Caused by: java.lang.IllegalStateException: No typehandler found for property createTime  at org.apache.ibatis.mapping.ResultMapping$Builder.validate(ResultMapping.java:151)  at org.apache.ibatis.mapping.ResultMapping$Builder.build(ResultMapping.java:140)  at org.apache.ibatis.builder.MapperBuilderAssistant.buildResultMapping(MapperBuilderAssistant.java:382)  at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildResultMappingFromContext(XMLMapperBuilder.java:378)  at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:280)  at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:252)  at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElements(XMLMapperBuilder.java:244)  at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:116)  ... 81 common frames omitted

解决方法如下:

直接加入如下依赖

<dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis-typehandlers-jsr310</artifactId>  <version>1.0.1</version> </dependency>

配置好这个依赖之后,就可以把Entity里面的Date替换成LocalDate、LocalDateTime了,其他的不用改

public class User {  private Integer id;  private String name;  private LocalDate createDate;  private LocalDateTime createTime; }

以上仅在mybatis 3.4.0版本中测试有效

如果使用的mybatis版本低于3.4.0,则还需要配置如下

<typeHandlers>  <typeHandler handler="org.apache.ibatis.type.InstantTypeHandler" />  <typeHandler handler="org.apache.ibatis.type.LocalDateTimeTypeHandler" />  <typeHandler handler="org.apache.ibatis.type.LocalDateTypeHandler" />  <typeHandler handler="org.apache.ibatis.type.LocalTimeTypeHandler" />  <typeHandler handler="org.apache.ibatis.type.OffsetDateTimeTypeHandler" />  <typeHandler handler="org.apache.ibatis.type.OffsetTimeTypeHandler" />  <typeHandler handler="org.apache.ibatis.type.ZonedDateTimeTypeHandler" /> </typeHandlers>

总结

以上就是mybatis使用Java8的日期LocalDate与LocalDateTime的实例的详细内容,更多请关注其它相关文章!

婚姻犹如一艘雕刻的船,看你怎样去欣赏它,又怎样驾驭它。

mybatis使用Java8的日期LocalDate与LocalDateTime的实例

相关文章:

你感兴趣的文章:

标签云: