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

DynamoDB插入数据Id类型不匹配问题及Java定义方式咨询

DynamoDB插入数据时的类型匹配问题

问题场景

我想要向DynamoDB中插入键值对,服务类中的初始插入方法如下:

protected PutItemResult insert(String table, String id, String key, String value){
    PutItemRequest request = new PutItemRequest()
        .withTableName(table)
        .addItemEntry("Id", new AttributeValue(id))
        .addItemEntry(key, new AttributeValue(value));
    return dynamoDbClient.putItem(request);
}

执行时触发错误:

One or more parameter values were invalid: Type mismatch for key Id expected: N actual: S

我理解Id应为数字类型,于是修改方法定义为:

insert(String table, Integer id, String key, String value){

但此时出现编译警告:

The constructor AttributeValue(Integer) is undefined

请问DynamoDB中Id的类型是什么?在Java中该如何正确定义?


问题分析与解决

  1. DynamoDB中Id的类型
    从错误信息可明确,你的DynamoDB表中Id字段被定义为数字类型(N类型),最初传入的字符串类型(S类型)与表结构定义不匹配,因此触发错误。

  2. Java中的正确实现方式
    AWS SDK的AttributeValue没有直接接收Integer的构造方法,需将数字转换为字符串形式传入,并明确指定类型为数字:

  • 推荐方式:使用withN()方法指定数字类型的值
protected PutItemResult insert(String table, Integer id, String key, String value){
    PutItemRequest request = new PutItemRequest()
        .withTableName(table)
        .addItemEntry("Id", new AttributeValue().withN(id.toString()))
        .addItemEntry(key, new AttributeValue(value));
    return dynamoDbClient.putItem(request);
}
  • 备选方式:直接传入数字的字符串形式(需确保id是合法数字字符串)
protected PutItemResult insert(String table, String id, String key, String value){
    PutItemRequest request = new PutItemRequest()
        .withTableName(table)
        .addItemEntry("Id", new AttributeValue(id))
        .addItemEntry(key, new AttributeValue(value));
    return dynamoDbClient.putItem(request);
}

另外,也可以根据业务需求调整DynamoDB表结构,将Id的主键类型改为字符串类型(S类型),这样就无需调整代码中的类型处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:54:52