mybatis使用Java8日期LocalDate和LocalDateTime mybatis怎样使用Java8的日期LocalDate和LocalDateTime详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mybatis使用Java8日期LocalDate和LocalDateTime mybatis怎样使用Java8的日期LocalDate和LocalDateTime详解

西夏一品堂   2021-03-29 我要评论
想了解mybatis怎样使用Java8的日期LocalDate和LocalDateTime详解的相关内容吗,西夏一品堂在本文为您仔细讲解mybatis使用Java8日期LocalDate和LocalDateTime的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:mybatis,localdate,java,localdatetime,java,date,mybatis,下面大家一起来学习吧。

前言

相信大家应该都知道,在实体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> 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们