本文介绍如何通过 Java SDK 为数据表设置主键列自增,以及如何为自增列写入数据并获取生成的自增值。
注意事项
表格存储 Java SDK 从 4.2.0 版本开始支持主键列自增。
自增列生成的自增值在分区键级别唯一且严格递增,但不保证连续。
前提条件
设置主键列自增
您可以在创建数据表时将非分区主键列设置为自增列,对于已创建的数据表,无法设置自增列。
说明
只有整型的主键列才能设置为自增列,一个数据表最多只能设置一个自增列,自增列生成的值为 64 位有符号长整型。
示例代码
以下示例代码创建了一个数据表 test_table,该表的主键包括分区键 id 和自增列 incr。
public static void createTableTest(SyncClient client) {
TableMeta tableMeta = new TableMeta("test_table");
tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("id", PrimaryKeyType.STRING));
tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("incr", PrimaryKeyType.INTEGER, PrimaryKeyOption.AUTO_INCREMENT));
TableOptions tableOptions = new TableOptions();
tableOptions.setMaxVersions(1);
tableOptions.setTimeToLive(-1);
CreateTableRequest createTableRequest = new CreateTableRequest(tableMeta, tableOptions);
client.createTable(createTableRequest);
}
写入数据
为自增列写入数据时,只需要将自增列的值设置为占位符。如果要获取生成的自增值用于数据查询和更新,还需要设置 rowPutChange 的返回类型为 RT_PK。
示例代码
以下示例代码在 test_table 表中写入一行数据,同时获取并打印写入行数据的主键信息。
public static void putRowTest(SyncClient client) {
// 构造主键
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
// 设置自增列为占位符
primaryKeyBuilder.addPrimaryKeyColumn("incr", PrimaryKeyValue.AUTO_INCREMENT);
PrimaryKey primaryKey = primaryKeyBuilder.build();
// 构造写入行数据
RowPutChange rowPutChange = new RowPutChange("test_table", primaryKey);
rowPutChange.addColumn("col1", ColumnValue.fromString("val1"));
// 设置返回类型为 RT_PK,返回写入行数据的主键信息
rowPutChange.setReturnType(ReturnType.RT_PK);
// 调用 putRow 方法写入行数据
PutRowRequest putRowRequest = new PutRowRequest();
putRowRequest.setRowChange(rowPutChange);
PutRowResponse putRowResponse = client.putRow(putRowRequest);
// RequestId 和 读写 CU 消耗
System.out.println("RequestId: " + putRowResponse.getRequestId());
System.out.println("Read CU Cost: " + putRowResponse.getConsumedCapacity().getCapacityUnit().getReadCapacityUnit());
System.out.println("Write CU Cost: " + putRowResponse.getConsumedCapacity().getCapacityUnit().getWriteCapacityUnit());
// 获取返回的主键信息并打印,如果不设置返回类型为 RT_PK,默认不返回主键信息
Row row = putRowResponse.getRow();
if(row != null)
System.out.println(row.getPrimaryKey().toString());
}
该文章对您有帮助吗?