azure-data-tables-java
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAzure Tables SDK for Java
Azure Tables SDK for Java
Build table storage applications using the Azure Tables SDK for Java. Works with both Azure Table Storage and Cosmos DB Table API.
使用Azure Tables SDK for Java构建表存储应用程序,同时兼容Azure Table Storage和Cosmos DB Table API。
Installation
安装
xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.6.0-beta.1</version>
</dependency>xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.6.0-beta.1</version>
</dependency>Client Creation
客户端创建
With Connection String
使用连接字符串
java
import com.azure.data.tables.TableServiceClient;
import com.azure.data.tables.TableServiceClientBuilder;
import com.azure.data.tables.TableClient;
TableServiceClient serviceClient = new TableServiceClientBuilder()
.connectionString("<your-connection-string>")
.buildClient();java
import com.azure.data.tables.TableServiceClient;
import com.azure.data.tables.TableServiceClientBuilder;
import com.azure.data.tables.TableClient;
TableServiceClient serviceClient = new TableServiceClientBuilder()
.connectionString("<your-connection-string>")
.buildClient();With Shared Key
使用共享密钥
java
import com.azure.core.credential.AzureNamedKeyCredential;
AzureNamedKeyCredential credential = new AzureNamedKeyCredential(
"<account-name>",
"<account-key>");
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.credential(credential)
.buildClient();java
import com.azure.core.credential.AzureNamedKeyCredential;
AzureNamedKeyCredential credential = new AzureNamedKeyCredential(
"<account-name>",
"<account-key>");
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.credential(credential)
.buildClient();With SAS Token
使用SAS令牌
java
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.sasToken("<sas-token>")
.buildClient();java
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.sasToken("<sas-token>")
.buildClient();With DefaultAzureCredential (Storage only)
使用DefaultAzureCredential(仅适用于存储服务)
java
import com.azure.identity.DefaultAzureCredentialBuilder;
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();java
import com.azure.identity.DefaultAzureCredentialBuilder;
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();Key Concepts
核心概念
- TableServiceClient: Manage tables (create, list, delete)
- TableClient: Manage entities within a table (CRUD)
- Partition Key: Groups entities for efficient queries
- Row Key: Unique identifier within a partition
- Entity: A row with up to 252 properties (1MB Storage, 2MB Cosmos)
- TableServiceClient:管理表(创建、列出、删除)
- TableClient:管理表中的实体(CRUD操作)
- Partition Key:对实体进行分组以实现高效查询
- Row Key:分区内的唯一标识符
- Entity:一行数据,最多包含252个属性(存储服务上限1MB,Cosmos上限2MB)
Core Patterns
核心模式
Create Table
创建表
java
// Create table (throws if exists)
TableClient tableClient = serviceClient.createTable("mytable");
// Create if not exists (no exception)
TableClient tableClient = serviceClient.createTableIfNotExists("mytable");java
// Create table (throws if exists)
TableClient tableClient = serviceClient.createTable("mytable");
// Create if not exists (no exception)
TableClient tableClient = serviceClient.createTableIfNotExists("mytable");Get Table Client
获取表客户端
java
// From service client
TableClient tableClient = serviceClient.getTableClient("mytable");
// Direct construction
TableClient tableClient = new TableClientBuilder()
.connectionString("<connection-string>")
.tableName("mytable")
.buildClient();java
// From service client
TableClient tableClient = serviceClient.getTableClient("mytable");
// Direct construction
TableClient tableClient = new TableClientBuilder()
.connectionString("<connection-string>")
.tableName("mytable")
.buildClient();Create Entity
创建实体
java
import com.azure.data.tables.models.TableEntity;
TableEntity entity = new TableEntity("partitionKey", "rowKey")
.addProperty("Name", "Product A")
.addProperty("Price", 29.99)
.addProperty("Quantity", 100)
.addProperty("IsAvailable", true);
tableClient.createEntity(entity);java
import com.azure.data.tables.models.TableEntity;
TableEntity entity = new TableEntity("partitionKey", "rowKey")
.addProperty("Name", "Product A")
.addProperty("Price", 29.99)
.addProperty("Quantity", 100)
.addProperty("IsAvailable", true);
tableClient.createEntity(entity);Get Entity
获取实体
java
TableEntity entity = tableClient.getEntity("partitionKey", "rowKey");
String name = (String) entity.getProperty("Name");
Double price = (Double) entity.getProperty("Price");
System.out.printf("Product: %s, Price: %.2f%n", name, price);java
TableEntity entity = tableClient.getEntity("partitionKey", "rowKey");
String name = (String) entity.getProperty("Name");
Double price = (Double) entity.getProperty("Price");
System.out.printf("Product: %s, Price: %.2f%n", name, price);Update Entity
更新实体
java
import com.azure.data.tables.models.TableEntityUpdateMode;
// Merge (update only specified properties)
TableEntity updateEntity = new TableEntity("partitionKey", "rowKey")
.addProperty("Price", 24.99);
tableClient.updateEntity(updateEntity, TableEntityUpdateMode.MERGE);
// Replace (replace entire entity)
TableEntity replaceEntity = new TableEntity("partitionKey", "rowKey")
.addProperty("Name", "Product A Updated")
.addProperty("Price", 24.99)
.addProperty("Quantity", 150);
tableClient.updateEntity(replaceEntity, TableEntityUpdateMode.REPLACE);java
import com.azure.data.tables.models.TableEntityUpdateMode;
// Merge (update only specified properties)
TableEntity updateEntity = new TableEntity("partitionKey", "rowKey")
.addProperty("Price", 24.99);
tableClient.updateEntity(updateEntity, TableEntityUpdateMode.MERGE);
// Replace (replace entire entity)
TableEntity replaceEntity = new TableEntity("partitionKey", "rowKey")
.addProperty("Name", "Product A Updated")
.addProperty("Price", 24.99)
.addProperty("Quantity", 150);
tableClient.updateEntity(replaceEntity, TableEntityUpdateMode.REPLACE);Upsert Entity
插入或更新实体(Upsert)
java
// Insert or update (merge mode)
tableClient.upsertEntity(entity, TableEntityUpdateMode.MERGE);
// Insert or replace
tableClient.upsertEntity(entity, TableEntityUpdateMode.REPLACE);java
// Insert or update (merge mode)
tableClient.upsertEntity(entity, TableEntityUpdateMode.MERGE);
// Insert or replace
tableClient.upsertEntity(entity, TableEntityUpdateMode.REPLACE);Delete Entity
删除实体
java
tableClient.deleteEntity("partitionKey", "rowKey");java
tableClient.deleteEntity("partitionKey", "rowKey");List Entities
列出实体
java
import com.azure.data.tables.models.ListEntitiesOptions;
// List all entities
for (TableEntity entity : tableClient.listEntities()) {
System.out.printf("%s - %s%n",
entity.getPartitionKey(),
entity.getRowKey());
}
// With filtering and selection
ListEntitiesOptions options = new ListEntitiesOptions()
.setFilter("PartitionKey eq 'sales'")
.setSelect("Name", "Price");
for (TableEntity entity : tableClient.listEntities(options, null, null)) {
System.out.printf("%s: %.2f%n",
entity.getProperty("Name"),
entity.getProperty("Price"));
}java
import com.azure.data.tables.models.ListEntitiesOptions;
// List all entities
for (TableEntity entity : tableClient.listEntities()) {
System.out.printf("%s - %s%n",
entity.getPartitionKey(),
entity.getRowKey());
}
// With filtering and selection
ListEntitiesOptions options = new ListEntitiesOptions()
.setFilter("PartitionKey eq 'sales'")
.setSelect("Name", "Price");
for (TableEntity entity : tableClient.listEntities(options, null, null)) {
System.out.printf("%s: %.2f%n",
entity.getProperty("Name"),
entity.getProperty("Price"));
}Query with OData Filter
使用OData过滤器查询
java
// Filter by partition key
ListEntitiesOptions options = new ListEntitiesOptions()
.setFilter("PartitionKey eq 'electronics'");
// Filter with multiple conditions
options.setFilter("PartitionKey eq 'electronics' and Price gt 100");
// Filter with comparison operators
options.setFilter("Quantity ge 10 and Quantity le 100");
// Top N results
options.setTop(10);
for (TableEntity entity : tableClient.listEntities(options, null, null)) {
System.out.println(entity.getRowKey());
}java
// Filter by partition key
ListEntitiesOptions options = new ListEntitiesOptions()
.setFilter("PartitionKey eq 'electronics'");
// Filter with multiple conditions
options.setFilter("PartitionKey eq 'electronics' and Price gt 100");
// Filter with comparison operators
options.setFilter("Quantity ge 10 and Quantity le 100");
// Top N results
options.setTop(10);
for (TableEntity entity : tableClient.listEntities(options, null, null)) {
System.out.println(entity.getRowKey());
}Batch Operations (Transactions)
批量操作(事务)
java
import com.azure.data.tables.models.TableTransactionAction;
import com.azure.data.tables.models.TableTransactionActionType;
import java.util.Arrays;
// All entities must have same partition key
List<TableTransactionAction> actions = Arrays.asList(
new TableTransactionAction(
TableTransactionActionType.CREATE,
new TableEntity("batch", "row1").addProperty("Name", "Item 1")),
new TableTransactionAction(
TableTransactionActionType.CREATE,
new TableEntity("batch", "row2").addProperty("Name", "Item 2")),
new TableTransactionAction(
TableTransactionActionType.UPSERT_MERGE,
new TableEntity("batch", "row3").addProperty("Name", "Item 3"))
);
tableClient.submitTransaction(actions);java
import com.azure.data.tables.models.TableTransactionAction;
import com.azure.data.tables.models.TableTransactionActionType;
import java.util.Arrays;
// All entities must have same partition key
List<TableTransactionAction> actions = Arrays.asList(
new TableTransactionAction(
TableTransactionActionType.CREATE,
new TableEntity("batch", "row1").addProperty("Name", "Item 1")),
new TableTransactionAction(
TableTransactionActionType.CREATE,
new TableEntity("batch", "row2").addProperty("Name", "Item 2")),
new TableTransactionAction(
TableTransactionActionType.UPSERT_MERGE,
new TableEntity("batch", "row3").addProperty("Name", "Item 3"))
);
tableClient.submitTransaction(actions);List Tables
列出表
java
import com.azure.data.tables.models.TableItem;
import com.azure.data.tables.models.ListTablesOptions;
// List all tables
for (TableItem table : serviceClient.listTables()) {
System.out.println(table.getName());
}
// Filter tables
ListTablesOptions options = new ListTablesOptions()
.setFilter("TableName eq 'mytable'");
for (TableItem table : serviceClient.listTables(options, null, null)) {
System.out.println(table.getName());
}java
import com.azure.data.tables.models.TableItem;
import com.azure.data.tables.models.ListTablesOptions;
// List all tables
for (TableItem table : serviceClient.listTables()) {
System.out.println(table.getName());
}
// Filter tables
ListTablesOptions options = new ListTablesOptions()
.setFilter("TableName eq 'mytable'");
for (TableItem table : serviceClient.listTables(options, null, null)) {
System.out.println(table.getName());
}Delete Table
删除表
java
serviceClient.deleteTable("mytable");java
serviceClient.deleteTable("mytable");Typed Entities
类型化实体
java
public class Product implements TableEntity {
private String partitionKey;
private String rowKey;
private OffsetDateTime timestamp;
private String eTag;
private String name;
private double price;
// Getters and setters for all fields
@Override
public String getPartitionKey() { return partitionKey; }
@Override
public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; }
@Override
public String getRowKey() { return rowKey; }
@Override
public void setRowKey(String rowKey) { this.rowKey = rowKey; }
// ... other getters/setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
// Usage
Product product = new Product();
product.setPartitionKey("electronics");
product.setRowKey("laptop-001");
product.setName("Laptop");
product.setPrice(999.99);
tableClient.createEntity(product);java
public class Product implements TableEntity {
private String partitionKey;
private String rowKey;
private OffsetDateTime timestamp;
private String eTag;
private String name;
private double price;
// Getters and setters for all fields
@Override
public String getPartitionKey() { return partitionKey; }
@Override
public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; }
@Override
public String getRowKey() { return rowKey; }
@Override
public void setRowKey(String rowKey) { this.rowKey = rowKey; }
// ... other getters/setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
// Usage
Product product = new Product();
product.setPartitionKey("electronics");
product.setRowKey("laptop-001");
product.setName("Laptop");
product.setPrice(999.99);
tableClient.createEntity(product);Error Handling
错误处理
java
import com.azure.data.tables.models.TableServiceException;
try {
tableClient.createEntity(entity);
} catch (TableServiceException e) {
System.out.println("Status: " + e.getResponse().getStatusCode());
System.out.println("Error: " + e.getMessage());
// 409 = Conflict (entity exists)
// 404 = Not Found
}java
import com.azure.data.tables.models.TableServiceException;
try {
tableClient.createEntity(entity);
} catch (TableServiceException e) {
System.out.println("Status: " + e.getResponse().getStatusCode());
System.out.println("Error: " + e.getMessage());
// 409 = Conflict (entity exists)
// 404 = Not Found
}Environment Variables
环境变量
bash
undefinedbash
undefinedStorage Account
Storage Account
AZURE_TABLES_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=...
AZURE_TABLES_ENDPOINT=https://<account>.table.core.windows.net
AZURE_TABLES_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=...
AZURE_TABLES_ENDPOINT=https://<account>.table.core.windows.net
Cosmos DB Table API
Cosmos DB Table API
COSMOS_TABLE_ENDPOINT=https://<account>.table.cosmosdb.azure.com
undefinedCOSMOS_TABLE_ENDPOINT=https://<account>.table.cosmosdb.azure.com
undefinedBest Practices
最佳实践
- Partition Key Design: Choose keys that distribute load evenly
- Batch Operations: Use transactions for atomic multi-entity updates
- Query Optimization: Always filter by PartitionKey when possible
- Select Projection: Only select needed properties for performance
- Entity Size: Keep entities under 1MB (Storage) or 2MB (Cosmos)
- 分区键设计:选择能均匀分配负载的键
- 批量操作:使用事务实现原子性多实体更新
- 查询优化:尽可能始终按PartitionKey进行过滤
- 选择投影:仅选择所需属性以提升性能
- 实体大小:保持实体大小在1MB以内(存储服务)或2MB以内(Cosmos)
Trigger Phrases
触发短语
- "Azure Tables Java"
- "table storage SDK"
- "Cosmos DB Table API"
- "NoSQL key-value storage"
- "partition key row key"
- "table entity CRUD"
- "Azure Tables Java"
- "table storage SDK"
- "Cosmos DB Table API"
- "NoSQL key-value storage"
- "partition key row key"
- "table entity CRUD"