You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DynamoDBTypeConverted失效,查询数据时抛出java.lang.ClassCastException

问题原因

  1. 查询方法参数类型不匹配:如果Repository查询方法中,针对sortKey的between条件传入的是Long类型而非LocalDate,框架会错误地将Long传入convert方法(该方法预期参数为LocalDate),触发类型转换异常。
  2. Spring Data DynamoDB版本bug:你使用的5.1.0版本在处理带自定义转换器的范围查询(如between)时存在逻辑错误,错误调用了转换器的convert方法,而非正确处理参数转换逻辑。

解决办法

方法1:修正查询方法参数类型

确保Repository中的查询方法参数为LocalDate类型,而非Long。示例:

// 错误写法
// List<PriceCalendar> findBySortKeyBetween(Long startDay, Long endDay);

// 正确写法
List<PriceCalendar> findBySortKeyBetween(LocalDate startDate, LocalDate endDate);

框架会自动调用LocalDateConverter.convert()将LocalDate转为Long,匹配DynamoDB存储类型,避免转换错误。

方法2:升级Spring Data DynamoDB版本

spring-data-dynamodb 5.1.0的该bug在后续版本已修复,建议升级到5.2.0及以上版本。
Maven依赖修改:

<dependency>
    <groupId>com.github.derjust</groupId>
    <artifactId>spring-data-dynamodb</artifactId>
    <version>5.2.0</version>
</dependency>

Gradle依赖修改:

implementation 'com.github.derjust:spring-data-dynamodb:5.2.0'

方法3:手动处理查询参数转换

若无法升级版本,可手动将LocalDate转为Long后,使用DynamoDB原生API查询:

Long startDay = startDate.toEpochDay();
Long endDay = endDate.toEpochDay();

DynamoDBQueryExpression<PriceCalendar> queryExpr = new DynamoDBQueryExpression<>()
    .withHashKeyValues(/* 设置哈希键对象 */)
    .withRangeKeyCondition("dateTimestamp", new Condition()
        .withComparisonOperator(ComparisonOperator.BETWEEN)
        .withAttributeValueList(
            new AttributeValue().withN(startDay.toString()),
            new AttributeValue().withN(endDay.toString())
        ));

List<PriceCalendar> results = dynamoDBMapper.query(PriceCalendar.class, queryExpr);

内容的提问来源于stack exchange,提问作者Tarik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:35:22