大家知道,在实体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>