广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot日期格式化及时差问题分析
  • 113
分享到

springboot日期格式化及时差问题分析

springboot日期格式化springboot时差 2022-12-10 12:12:50 113人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录前言一、Mysql中日期字段的正确设置二、日期格式化,时差1. 日期字段返回格式不正确–方案一2.日期字段返回格式不正确–方案二二、日期无法自动填充总结提

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

前言

随着mysql8.0的问世,里面确实增加了很多功能,例如之前我发表的文章,数据库层面的递归查询等;不过也随之而来带来了一些不兼容的问题,比如group by 报错,还有就是日期时差问题;

一、mysql中日期字段的正确设置

create_time timestamp default CURRENT_TIMESTAMP not null comment '创建时间',
update_time timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '修改时间'

创建时间会自动获取当前时间
修改数据的时候,会自动更新 修改时间,免去了每次程序都要设置的麻烦

二、日期格式化,时差

1. 日期字段返回格式不正确–方案一

例如一个实体中内容如下

@Data
public class AAA{
   //创建时间
    private Date createTime;
    //修改时间
    private Date updateTime;
 }

这样的话,返回的日期格式就错误的,其次也会导致时间会早于数据库的真正时间八小时。我们可以有两种选择,直接对当前字段设置日期格式

@JSONFORMat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//取日期时使用
   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")//存日期时使用

也就是这样

@Data
public class AAA{
   //创建时间
   @jsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//取日期时使用
   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")//存日期时使用
    private Date createTime;
    //修改时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//取日期时使用
   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")//存日期时使用
    private Date updateTime;
 }

是不是很烦呀每次都要对每个实体类中的每个日期字段都添加

2.日期字段返回格式不正确–方案二

全局设置日期格式化的格式,并且全局声名所有日期 的 补差 八小时,设置yml即可

spring:
  profiles:
    active: dev
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

二、日期无法自动填充

由于我已经设置了创建时间的自动填充,和修改时间的自动修改,在数据库层面已经没有问题了,但是当我用mybatis的时候,由于insertselective 等的字段非空判断,导致就不会生成创建时间和修改时间;咋搞?

对于次问题,我们通过拦截器,全局设置自动填充日期等统一信息,还可以有创建人,修改人等;

1. mybatis-plus

由于mp提供了注解,我们可以通过设置一个注解就可以搞定填充问题

@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

2. mybatis 只能靠自己了

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;


@Slf4j
@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        log.debug("------sqlId------" + mappedStatement.getId());

        // sql类型:insert、update、select、delete
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        if (parameter == null) {
            return invocation.proceed();
        }

        // 当sql为新增或更新类型时,自动填充操作人相关信息
        if (SqlCommandType.INSERT == sqlCommandType) {

            Field[] fields = getAllFields(parameter);
            for (Field field : fields) {
                try {
                    //注入创建时间
                    if ("createTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                    //注入修改时间
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    log.error("failed to insert data, exception = ", e);
                }
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {

            Field[] fields = getAllFields(parameter);
            for (Field field : fields) {
                try {
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    log.error("failed to update data, exception = ", e);
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

    
    private Field[] getAllFields(Object object) {
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

}

1 MybatisInterceptor
2 MybatisConfiguration
废话不多说,直接上代码

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;


@Slf4j
@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        log.debug("------sqlId------" + mappedStatement.getId());

        // sql类型:insert、update、select、delete
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        if (parameter == null) {
            return invocation.proceed();
        }

        // 当sql为新增或更新类型时,自动填充操作人相关信息
        if (SqlCommandType.INSERT == sqlCommandType) {

            Field[] fields = getAllFields(parameter);
            for (Field field : fields) {
                try {
                    //注入创建时间
                    if ("createTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                    //注入修改时间
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    log.error("failed to insert data, exception = ", e);
                }
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {

            Field[] fields = getAllFields(parameter);
            for (Field field : fields) {
                try {
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    log.error("failed to update data, exception = ", e);
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

    
    private Field[] getAllFields(Object object) {
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

}

@Configuration
public class MybatisConfiguration {

    
    @Bean
    public MybatisInterceptor getMybatisInterceptor() {
        return new MybatisInterceptor();
    }
}

总结

如上就解决了大部分项目中时间的问题,欢迎讨论,咨询~~

到此这篇关于SpringBoot日期格式化,时差问题的文章就介绍到这了,更多相关springboot日期格式化内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: springboot日期格式化及时差问题分析

本文链接: https://www.lsjlt.com/news/174762.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作