1. 程式人生 > 資料庫 >LocalDateTime與mysql日期型別的互動(基於mybatis)

LocalDateTime與mysql日期型別的互動(基於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  

複製程式碼

 匯入依賴

複製程式碼

<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

 

原文地址:https://www.cnblogs.com/carrychan/p/9883293.html