TableStore:单行操作

首先需要添加TableStore的依赖

<dependency>
    <groupId>com.aliyun.openservices</groupId>
    <artifactId>tablestore</artifactId>
    <version>4.10.2</version>
</dependency>

运行项目时可能会出现SLF4J相关的红字提示:

该提示不影响使用,如果觉得不爽的话,可以添加下面依赖去除:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.26</version>
</dependency>

1、根据主键查询数据(主键只有一个)

package com.example.demo;

import
com.alicloud.openservices.tablestore.SyncClient; import com.alicloud.openservices.tablestore.model.Column; import com.alicloud.openservices.tablestore.model.GetRowRequest; import com.alicloud.openservices.tablestore.model.GetRowResponse; import com.alicloud.openservices.tablestore.model.PrimaryKey; import com.alicloud.openservices.tablestore.model.PrimaryKeyBuilder; import com.alicloud.openservices.tablestore.model.PrimaryKeyValue; import com.alicloud.openservices.tablestore.model.Row; import com.alicloud.openservices.tablestore.model.SingleRowQueryCriteria; public class Query { public static void main(String[] args) { final String endPoint = "实例访问地址"; final String accessKeyId = "accessKeyId"; final String accessKeySecret = "accessKeySecret"; // 实例名 final String instanceName = "owlforest"; SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName); // 构造主键 PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder(); primaryKeyBuilder.addPrimaryKeyColumn("noteid", PrimaryKeyValue.fromLong(1)); PrimaryKey primaryKey = primaryKeyBuilder.build();
SingleRowQueryCriteria criteria = new SingleRowQueryCriteria("note", primaryKey);
// 设置读取最新版本 criteria.setMaxVersions(1);
// 读取所有数据 GetRowResponse getRowResponse
= client.getRow(new GetRowRequest(criteria)); Row row = getRowResponse.getRow(); // 遍历所有列 Column[] columns = row.getColumns(); for (Column column : columns) { System.out.println("Name:" + column.getName() + " Value:" + column.getValue()); } } }

如果只需要读取指定列,可以这样设置:

// 设置读取某些列
String[] a = { "author" };
criteria.addColumnsToGet(a);
GetRowResponse getRowResponse2 = client.getRow(new GetRowRequest(criteria));
Row row2 = getRowResponse2.getRow();
Column[] columns2 = row2.getColumns();
for (Column column : columns2) {
    System.out.println("Name:" + column.getName() + " Value:" + column.getValue());
}

经测试,criteria.addColumnsToGet("author");这么设置运行也不会报错,不过仍然会读出所有属性。

猜你喜欢

转载自www.cnblogs.com/wsfu/p/10535414.html
今日推荐