mybatis实体类映射:mysql中datetime类型与Java中localdatetime类型

本文探讨了在Spring Boot应用中,如何通过添加mybatis-typehandlers-jsr310依赖并配置实体类注解,处理数据库datetime类型与LocalDateTime类型的映射问题。接着介绍了如何通过引入jackson-datatype-jsr310解决序列化时的Java 8 LocalDateTime不支持问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:数据库中变量类型为datetime,实体类中变量类型为localdatetime,在进行查询数据库操作时,查询结果不能进行自动映射,报错信息如下:

2022-07-29 14:43:08.705 ERROR [http-nio-83-exec-10] o.a.c.c.C.[.[localhost].[/].[dispatcherServlet] >> Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Error attempting to get column 'reportDate' from result set.  Cause: java.sql.SQLFeatureNotSupportedException: getObject with type
; getObject with type; nested exception is java.sql.SQLFeatureNotSupportedException: getObject with type] with root cause
java.sql.SQLFeatureNotSupportedException: getObject with type

解决方案:

  1. pom.xml文件中添加依赖

    <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-typehandlers-jsr310</artifactId>
            <version>1.0.1</version>
    </dependency>
    
  2. 对应实体类中添加注解

    在这里插入图片描述
    之后再进行数据库查询,可以将数据库中的datetime类型数据映射为实体类中localdatetime类型,但在进行查询结果返回时出错,报错信息如下:

2022-07-29 14:50:33.204 ERROR [http-nio-83-exec-6] com.**.**.**.util.Utils >> toJson
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: java.util.ArrayList[0]->com.**.**.entity.Statisticv2Apps["reportdate"])

解决方法:

  1. pom.xml文件中添加依赖

    <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.13.0</version>
    </dependency>
    
  2. 进行模块注册

    private static final ObjectMapper objectMapper = new ObjectMapper();
    public static String toJson(Object data){
            try {
                //模块注册
                objectMapper.registerModule(new JavaTimeModule());
                return data == null ? null : objectMapper.writeValueAsString(data);
            } catch (JsonProcessingException e) {
                LOGGER.error("toJson",e);
                return null;
            }
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值