在使用Spring boot搭建的web项目中,如何使用消息转换器设置Mybatis映射实体类对象中的时间格式

在Springboot项目中使用Mybatis操作数据库时,可能会遇到时间格式转换的问题。解决方法包括在实体类成员变量上使用@JsonFormat注解定义时间格式,以及创建自定义配置类,重写extendMessageConverters方法,通过扩展MappingJackson2HttpMessageConverter并设置自定义的对象映射器,来统一处理时间的序列化和反序列化。
摘要由CSDN通过智能技术生成

        在使用Spring boot搭建web项目,我们通常都会使用到数据库,而使用mybatis存取数据库时间数据时,可能会出现一些格式转换的问题,本文将介绍两种配置时间格式的方法。

        1. 在实体类的成员变量上加上对应的注解

    //import com.fasterxml.jackson.annotation.JsonFormat;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private LocalDateTime beginTime;
    

        @JasonFormat可以定义时间格式,当在成员变量上加上这个注解时,使用mybatis从数据库中取时间数据就不会出现格式问题了。

        2. 定义一个配置类,在配置类中重写extendMessageConverters(扩展消息转换器)方法来实现对时间格式的定义.

        在方法中,我们先创建一个消息转换器对象,然后设置该对象的中的对象映射器(mybatis与java实体类对象中的映射规则),最后将该消息转换器对象加入到SpringMVC中的转换器集合里即可.

具体实现:

        自定义对象映射器:

package com.sky.json;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;

/**
 * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
 * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
 */
public class JacksonObjectMapper extends ObjectMapper {

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    public JacksonObjectMapper() {
        super();
        //收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);

        //反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        SimpleModule simpleModule = new SimpleModule()
                //日期格式反序列化
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
                //日期格式序列化规则
                .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
                .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
                .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        //注册功能模块 例如,可以添加自定义序列化器和反序列化器
        this.registerModule(simpleModule);
    }
}
import com.sky.json.JacksonObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * 配置类,注册web层相关组件
 */
@Configuration

public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

        //创建一个消息转换器对象
        MappingJackson2HttpMessageConverter mc = new MappingJackson2HttpMessageConverter();
        //设置对象转换器,将Java对象转化为json字符串
        mc.setObjectMapper(new JacksonObjectMapper());
        //将创建的转换器对象加入到spring MVC框架中
        converters.add(0,mc);
    }

}

注: 将消息转换器加入集合时,需要将我们自定义的对象添加到SpringMVC中已有的消息转换器对象之前,因为其生效规则是安顺序生效的,我们可以直接将其添加到索引为0的位置,一劳永逸。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用 Spring BootMyBatis 进行连表查询时,可以通过递归的方式将查询结果转换成树状结构的数据。 假设有两张表:部门表和员工表,部门表有一个 parent_id 字段表示该部门的上级部门,员工表有一个 dept_id 字段表示该员工所在的部门。现在需要查询出所有部门以及下属员工,并将其转换成树状结构的数据。 首先,需要定义一个部门实体类和一个员工实体类,代码如下: ```java public class Department { private Long id; private String name; private Long parentId; private List<Employee> employees; // getter 和 setter 略 } public class Employee { private Long id; private String name; private Long deptId; // getter 和 setter 略 } ``` 接下来,可以使用 MyBatis 进行连表查询,代码如下: ```xml <select id="getDepartments" resultMap="departmentResultMap"> select d.id, d.name, d.parent_id, e.id as employee_id, e.name as employee_name, e.dept_id as employee_dept_id from department d left join employee e on d.id = e.dept_id order by d.id, e.id </select> <resultMap id="departmentResultMap" type="Department"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="parentId" column="parent_id"/> <collection property="employees" ofType="Employee" resultMap="employeeResultMap" columnPrefix="employee_"/> </resultMap> <resultMap id="employeeResultMap" type="Employee"> <id property="id" column="employee_id"/> <result property="name" column="employee_name"/> <result property="deptId" column="employee_dept_id"/> </resultMap> ``` 注意,这里使用MyBatis 的 resultMap 来映射查询结果到实体类。 接下来,可以编写一个递归方法,将查询结果转换成树状结构的数据,代码如下: ```java private List<Department> buildTree(List<Department> departments) { Map<Long, Department> map = new HashMap<>(); for (Department department : departments) { map.put(department.getId(), department); } List<Department> roots = new ArrayList<>(); for (Department department : departments) { Long parentId = department.getParentId(); if (parentId == null || parentId == 0) { roots.add(department); } else { Department parent = map.get(parentId); if (parent != null) { parent.getEmployees().add(department.getEmployees().get(0)); } } } for (Department root : roots) { buildChildren(map, root); } return roots; } private void buildChildren(Map<Long, Department> map, Department department) { List<Department> children = new ArrayList<>(); for (Employee employee : department.getEmployees()) { Department child = map.get(employee.getDeptId()); if (child != null) { children.add(child); buildChildren(map, child); } } department.setChildren(children); } ``` 最后,在控制器调用这个递归方法即可,代码如下: ```java @GetMapping("/departments") public List<Department> getDepartments() { List<Department> departments = departmentMapper.getDepartments(); return buildTree(departments); } ``` 这样就可以返回树状结构的数据了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值