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中该如何正确定义?
问题分析与解决
DynamoDB中Id的类型
从错误信息可明确,你的DynamoDB表中Id字段被定义为数字类型(N类型),最初传入的字符串类型(S类型)与表结构定义不匹配,因此触发错误。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
相关产品推荐
相关产品推荐

