mybatis与mysql数据库交互时使用LocalDate类等


在做项目的时候,遇到数据库中想存入字段类型为Date类并且只存入yyyy-MM-dd这种只有日期的格式,但是java.util.date和java.sql.date都需要转换,不是特别的方便.然后后来学习过java8中关于日期的新的类LocalDate,这个可以直接返回一个日期格式为yyyy-MM-dd的,但是返回的类型确实Localdate类型的,此时的我就比较懵了,没有进一步的学习,现在终于有空学习一下了,在这里记录一下,就是解决我们使用localdate类没有办法和数据库中date类型存储数据的问题.我们知道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  

那么我们应该如何解决这个问题呢?

如果是Mybatis3.4.5之前的版本,需要添加一个依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>
        <!-- mybatis数据库字段类型映射,此处是重点 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-typehandlers-jsr310</artifactId>
            <version>1.0.1</version>
        </dependency>
        <!-- MYSQL驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

如果是Mybatis3.4.5之后,则不需要添加了,因为已经支持了上面的依赖的内容。个人推荐使用3.4.5之后的。我们只需要知道对应time类下对应的那些localdate类需要对应到数据库的哪一个类型就可以了。

上面就是一个数据库中的类型和pojo类中日期类型的对应。

只需要在类型对应好,便可以像普通的数据类型一样去实现交互了。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM