众所周知,在实体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  

导入依赖

<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>

属性配置

spring.datasource.url=jdbc:mysql://localhost:3306/dev?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# 如果想看到mybatis日志需要做如下配置
logging.level.com.carry=DEBUG
######### Mybatis 自身配置 ##########
mybatis.mapper-locations=classpath:com/carry/mapper/*Mapper.xml
mybatis.type-aliases-package=com.carry.dto
# 驼峰命名规范 如:数据库字段是 order_id 那么 实体字段就要写成 orderId
mybatis.configuration.map-underscore-to-camel-case=true
######### 通用Mapper ##########
# 主键自增回写方法,默认值MYSQL,详细说明请看文档
mapper.identity=MYSQL
mapper.mappers=tk.mybatis.mapper.common.Mapper
# 设置 insert 和 update 中,是否判断字符串类型!=''
mapper.not-empty=true
# 枚举按简单类型处理
mapper.enum-as-simple-type=true

建表SQL

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`create_date` date DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)

实体类

package com.carry.dto;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id; import com.fasterxml.jackson.annotation.JsonFormat; public class User implements Serializable{ private static final long serialVersionUID = -108907189034815108L; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate createDate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public LocalDate getCreateDate() {
return createDate;
} public void setCreateDate(LocalDate createDate) {
this.createDate = createDate;
} public LocalDateTime getCreateTime() {
return createTime;
} public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
} }

Mapper类

package com.carry.mapper;

import com.carry.dto.User;

import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {

}

启动类

package com.carry;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication
@MapperScan(basePackages = "com.carry.mapper")
public class SpringBootDateMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDateMysqlApplication.class, args);
}
}

测试

package com.carry;

import java.time.LocalDate;
import java.time.LocalDateTime; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.carry.dto.User;
import com.carry.mapper.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDateMysqlApplicationTests { @Autowired
private UserMapper mapper; @Autowired
private ObjectMapper objectMapper; @Test
public void insert() {
User user = new User();
user.setCreateDate(LocalDate.now());
user.setCreateTime(LocalDateTime.now());
mapper.insertSelective(user);
} @Test
public void query() {
mapper.selectAll().stream().forEach(e -> {
try {
System.out.println(objectMapper.writeValueAsString(e));
} catch (JsonProcessingException ex) {
ex.printStackTrace();
}
});
}
}

先后执行测试方法 insert 和 query,无错误说明测试通过

SpringBootDateMysql

LocalDateTime与mysql日期类型的交互(基于mybatis)的更多相关文章

  1. mysql 日期类型比较

    MySQL 日期类型:日期格式.所占存储空间.日期范围 比较. 日期类型        存储空间       日期格式                 日期范围 ------------ ------ ...

  2. 转 MySQL 日期类型详解

    MySQL 日期类型:日期格式.所占存储空间.日期范围 比较.  日期类型        存储空间       日期格式                 日期范围  ------------ ---- ...

  3. MySQL 日期类型及默认设置 (除timestamp类型外,系统不支持其它时间类型字段设置默认值)

    MySQL 日期类型及默认设置 之前在用 MySQL 新建 table,创建日期类型列时遇到了一些问题,现在整理下来以供参考. MySQL 的日期类型如何设置当前时间为其默认值? 答:请使用 time ...

  4. java mysql 日期类型

    mysql(版本:5.1.50)的时间日期类型如下: datetime 8bytes xxxx-xx-xx xx:xx:xx 1000-01-01 00:00:00到9999-12-31 23:59: ...

  5. Mysql日期类型大小比较---拉取给定时间段的记录

    我们知道,mysql里边,日期类型有很多表现形式,date, datetime,timestamp等类型.考虑这样一种场景: 按时间段拉取给定时间段的内容,这时,我们就得使用日期类型的比较了. 表结构 ...

  6. mysql日期类型

    日期类型 DATE TIME DATETIME TIMESTAMP YEAR 作用:存储用户注册时间,文章发布时间,员工入职时间,出生时间,过期时间等 YEAR YYYY(1901/2155) DAT ...

  7. mysql日期类型默认值'0000-00-00'容错处理

    mysql日期默认值'0000-00-00'惹的祸 .net连mysql数据库时,如果表里有字段是日期型且值是‘0000-00-00’时,会报错.在C#里面日期不可能是那样的.或许是最小日期定义的差别 ...

  8. MySQL 日期类型函数及使用

    1 MySQL 数据库中有五种与日期时间有关的数据类型,各种日期数据类型所占空间如下图所示: 2 datetime 与 date datetime 占用8字节,是占用空间最多的一种日期格式.它显示日期 ...

  9. MySQL:日期类型

    1. datetime(年月日时分秒) 格式:‘YYY-MM-DD HH:MM:SS’. 占用:8字节 范围:1000-01-01 00:00:00 到 9999-12-31 23:59:59. ti ...

随机推荐

  1. SpringCloud学习笔记(14)----Spring Cloud Netflix之Hystrix对Feign的支持

    1. Hystrix对Feign的支持 添加Feign中IUserBiz的实现类HystrixFallBack: package com.wangx.cloud.springcloud02consum ...

  2. 使用IDEA在Maven中创建MyBatis逆向工程以及需要注意的问题(入门)

    逆向工程简介: mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java.mapper.xml.pojo…),可以让程序员将更多的精力放在繁杂的业务逻 ...

  3. Hadoop_MapReduce中Mapper类和Reduce类

    在权威指南中,有个关于处理温度的MapReduce类,具体如下: 第一部分:Map public class MaxTemperatureMapper extends MapReduceBase im ...

  4. [AHOI2013]作业 莫队 树状数组

    #include<cmath> #include<cstdio> #include<algorithm> #include<string> #inclu ...

  5. 12种CSS BUG解决方法与技巧

    一. 针对浏览器的选择器 这些选择器在你需要针对某款浏览器进行css设计时将非常有用. IE6及其更低版本,本文由52CSS.com整理,转载请注明出处! * html {} IE7及其更低版本 *: ...

  6. How Javascript works (Javascript工作原理) (二) 引擎,运行时,如何在 V8 引擎中书写最优代码的 5 条小技巧

    个人总结: 一个Javascript引擎由一个标准解释程序,或者即时编译器来实现. 解释器(Interpreter): 解释一行,执行一行. 编译器(Compiler): 全部编译成机器码,统一执行. ...

  7. @GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping

    @GetMapping.@PostMapping.@PutMapping.@DeleteMapping.@PatchMapping  @GetMapping是一个组合注解,是@RequestMappi ...

  8. MarkDown写作之嵌入LaTeX和HTML

    本系列文章由 @YhL_Leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/49788741 Markdown 是一种 ...

  9. 洛谷 P3671 [USACO17OPEN]Where's Bessie? 贝西在哪呢

    P3671 [USACO17OPEN]Where's Bessie? 贝西在哪呢 题目背景 农夫John正在测试一个他新发明的全自动寻找奶牛无人机,它能够照一张农场的图片然后自动找出奶牛的位置. 不幸 ...

  10. [MST] Attach Behavior to mobx-state-tree Models Using Actions

    Models are not just a nifty feature for type checking. They enable you to attach behavior to your ac ...