SpringBoot,Mybatis 使用Java8(JSR310)时间日期规范


一. 依赖

⏹若使用的是SpringBoot

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.0.0</version>
</dependency>
  • 2.0.0以上的版本就支持JSR310时间规范。

⏹若使用的是Spring

<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-spring</artifactId>
	<version>2.0.5</version>
</dependency>
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.5</version>
</dependency>
  • Mybatis在3.4.5版本(2017.8月份发布)之后,就内置了对jsr310的支持。

二. 前台

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSR310日期测试</title>
</head>
<body>
    <button id="btn1">点击发送请求</button>
</body>
<script th:src="@{/js/public/jquery-3.6.0.min.js}"></script>
<script th:inline="javascript">
	$("#btn1").click(function() {
      
      
		
		// 各种时间格式
		const data = {
      
      
			date1: "2020/03/07 12:10:01",
			date2: "2020-03-06",
			date3: "12:10",
			date5: "202003",
			dateA: "2020/03/07",
			dateB: "2020年03月07日",
			dateC: "20200307",
		}
		
	    $.ajax({
      
      
	        url: "/test03/jsr310date",
	        type: 'POST',
	        data: JSON.stringify(data),
	        contentType: 'application/json;charset=utf-8',
	        success: function (data, status, xhr) {
      
      
	            console.log(data);
	        }
	    });
	});
</script>
</html>

三. Controller,Form,Service

⏹Controller

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/test03")
public class Test03Controller {
    
    
	
	@Resource
	private Test03Service service;

	@GetMapping("/init")
	public ModelAndView init() {
    
    
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("test03");
		return modelAndView;
	}
	
	@PostMapping("/jsr310date")
	@ResponseBody
	public Test03Entity jsr310date(@RequestBody Test03Form form) throws Exception {
    
    
		
		return service.jsr310date(form);
	}
}

⏹Form

  • 后台使用LocalDate等时间类型接收前台数据时,需要使用@JsonFormat注解来指定数据格式。
  • @JsonFormat注解能指定前台向后台传入的数据类型,同时后台向前台返回的数据格式也会受其影响。
  • 若不想在每个字段上都添加@JsonFormat注解来指定格式,可以使用全局日期格式转换器,
    详情请参考这篇博客:SpringBoot Java8日期全局日期格式转换器
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.Data;

@Data
public class Test03Form {
    
    
	
	@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")
	private LocalDateTime date1;
	
	// yyyy-MM-dd 格式的日期字符串,可自动封装到LocalDate中
	private LocalDate date2;
	
	@JsonFormat(pattern = "HH:mm")
	private LocalTime date3;
	
	private Instant date4;
	
	// 年月时间格式也可直接封装
	@JsonFormat(pattern = "yyyyMM")
	private YearMonth date5;
	
	// yyyy-MM-dd 格式之外的日期字符串,需要通过@JsonFormat注解指定格式
	@JsonFormat(pattern = "yyyy/MM/dd")
	private LocalDate dateA;
	
	// 约束前端和后端的数据格式
	@JsonFormat(pattern = "yyyy年MM月dd日") 
	private LocalDate dateB;
	
	@JsonFormat(pattern = "yyyyMMdd")
	private LocalDate dateC;	
}

⏹Service

  • 向数据库中插入数据后,再查询插入的数据,返回前台查看效果。
import java.time.Instant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class Test03Service {
    
    
	
	@Autowired
	private TestMapper03 mapper;

	@Transactional(rollbackFor = Exception.class)
	public Test03Entity jsr310date(Test03Form form) {
    
    
		
		form.setDate4(Instant.now());
		mapper.insertData(form);

		// 查询插入数据库中的数据
		return mapper.selectData();
	}
}

四. 数据库类型

⏹使用的是Mysql数据库,其中实体类属性和DB字段类型的对应关系如下

实体类属性 DB字段类型
LocalDateTime datetime
LocalDate date
LocalTime time
Instant timestamp

在这里插入图片描述


五. 效果

  • 因为date4是时间戳类型,所以返回到前台的数据格式为: "2023-09-15T01:22:18Z"
  • 在前台时间戳可以通过new Date("2023-09-15T01:22:18Z")来转换为Date类型。
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/feyehong/article/details/132893928