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字段类型
LocalDateTimedatetime
LocalDatedate
LocalTimetime
Instanttimestamp

在这里插入图片描述


五. 效果

  • 因为date4是时间戳类型,所以返回到前台的数据格式为: "2023-09-15T01:22:18Z"
  • 在前台时间戳可以通过new Date("2023-09-15T01:22:18Z")来转换为Date类型。
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring BootMyBatis的组合可以简化开发过程,并提供更好的开发体验。在使用Spring BootMyBatis时,你可以使用mybatis-spring-boot-starter来进行配置。这个starter可以让你完全使用注解而不需要配置文件,也可以通过简单的配置轻松上手。具体而言,你需要遵循以下步骤来使用Spring BootMyBatis: 1. 首先,在你的pom文件中添加对mybatis-spring-boot-starter的依赖。这个依赖会自动引入必要的依赖项,包括MyBatisSpring Boot的集成。 2. 在application.properties文件中添加MyBatis的相关配置。其中,你需要指定mybatis.config-location属性来指定MyBatis的配置文件位置,通常是在resources目录下的mybatis-config.xml文件。同时,你还需要指定mybatis.mapper-locations属性来指定Mapper接口的XML映射文件所在的位置,通常是在resources目录下的mapper目录。 3. 创建实体类和Mapper接口。实体类用于映射数据库表的字段,而Mapper接口用于定义数据库操作的方法。 4. 在Mapper接口的方法上使用注解来定义SQL语句。通过注解,你可以直接在方法上编写SQL语句,而不需要再编写XML映射文件。 5. 在Service或Controller层中使用@Autowired注解来注入Mapper接口,并调用其中的方法来进行数据库操作。 通过以上步骤,你就可以使用Spring BootMyBatis来进行数据库操作了。这种方式可以大大简化配置和开发过程,并提供更好的开发体验。同时,你也可以根据具体的需求来使用MyBatis的其他功能,比如动态SQL、分页查询等。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Spring BootMybatis使用](https://blog.csdn.net/herry66/article/details/122699454)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值