azure-data-tables-java
microsoft/skills
使用 Azure Tables SDK for Java 建置表格儲存應用程式,該 SDK 同時支援 Azure 表格儲存和 Cosmos DB 表格 API,適用於 NoSQL 鍵值資料。
...展開全部Azure 表格 SDK(Java 版)
使用 Azure 表格 SDK(Java 版)建置表格儲存應用程式。此 SDK 同時支援 Azure 表格儲存和 Cosmos DB 表格 API。
安裝
com.azure
azure-data-tables
12.6.0-beta.1
建立客戶端
使用連線字串
import com.azure.data.tables.TableServiceClient;
import com.azure.data.tables.TableServiceClientBuilder;
import com.azure.data.tables.TableClient;
TableServiceClient serviceClient = new TableServiceClientBuilder()
.connectionString("")
.buildClient();
使用共用金鑰
import com.azure.core.credential.AzureNamedKeyCredential;
AzureNamedKeyCredential credential = new AzureNamedKeyCredential(
"",
"");
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("")
.credential(credential)
.buildClient();
使用 SAS 憑證
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("")
.sasToken("")
.buildClient();
使用 DefaultAzureCredential(僅限儲存體)
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// 本地開發環境:DefaultAzureCredential。生產環境:將 AZURE_TOKEN_CREDENTIALS 設定為 prod 或 AZURE_TOKEN_CREDENTIALS=
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// 或者在生產環境中直接使用特定憑證:
// 參閱 https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("")
.credential(credential)
.buildClient();
關鍵概念
- TableServiceClient:管理資料表(建立、列出、刪除)
- TableClient:管理表格內的實體(CRUD)
- 分區鍵:將實體分組以提升查詢效率
- 行鍵:分區內的唯一識別碼
- 實體:一筆最多包含 252 個屬性的資料列(1MB Storage,2MB Cosmos)
核心模式
建立資料表
// 建立資料表(若已存在則拋出例外)
TableClient tableClient = serviceClient.createTable("mytable");
// 若不存在則建立(不拋出例外)
TableClient tableClient = serviceClient.createTableIfNotExists("mytable");
取得表格客戶端
// 從服務客戶端取得
TableClient tableClient = serviceClient.getTableClient("mytable");
// 直接建構
TableClient tableClient = new TableClientBuilder()
.connectionString("")
.tableName("mytable")
.buildClient();
建立實體
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);
取得實體
TableEntity 實體 = tableClient.getEntity("partitionKey", "rowKey");
String name = (String) entity.getProperty("Name");
Double price = (Double) entity.getProperty("Price");
System.out.printf("產品:%s,價格:%.2f%n", name, price);
更新實體
import com.azure.data.tables.models.TableEntityUpdateMode;
// 合併 (僅更新指定屬性)
TableEntity updateEntity = new TableEntity("partitionKey", "rowKey")
.addProperty("Price", 24.99);
tableClient.updateEntity(updateEntity, TableEntityUpdateMode.MERGE);
// 取代(取代整個實體)
TableEntity replaceEntity = new TableEntity("partitionKey", "rowKey")
.addProperty("Name", "Product A Updated")
.addProperty("Price", 24.99)
.addProperty("數量", 150);
tableClient.updateEntity(replaceEntity, TableEntityUpdateMode.REPLACE);
Upsert 實體
// 插入或更新(合併模式)
tableClient.upsertEntity(entity, TableEntityUpdateMode.MERGE);
// 插入或取代
tableClient.upsertEntity(entity, TableEntityUpdateMode.REPLACE);
刪除實體
tableClient.deleteEntity("partitionKey", "rowKey");
列出實體
import com.azure.data.tables.models.ListEntitiesOptions;
// 列出所有實體
for (TableEntity entity : tableClient.listEntities()) {
System.out.printf("%s - %s%n",
entity.getPartitionKey(),
entity.getRowKey());
}
// 帶有篩選與選取條件
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"));
}
使用 OData 篩選條件進行查詢
// 根據分區金鑰篩選
ListEntitiesOptions options = new ListEntitiesOptions()
.setFilter("PartitionKey eq 'electronics'");
// 使用多個條件進行篩選
options.setFilter("PartitionKey eq 'electronics' and Price gt 100");
// 使用比較運算子進行篩選
options.setFilter("Quantity ge 10 and Quantity le 100");
// 前 N 筆結果
options.setTop(10);
for (TableEntity entity : tableClient.listEntities(options, null, null)) {
System.out.println(entity.getRowKey());
}
批次操作(交易)
import com.azure.data.tables.models.TableTransactionAction;
import com.azure.data.tables.models.TableTransactionActionType;
import java.util.Arrays;
// 所有實體必須具有相同的分區鍵
List 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);
列出表格
import com.azure.data.tables.models.TableItem;
import com.azure.data.tables.models.ListTablesOptions;
// 列出所有資料表
for (TableItem table : serviceClient.listTables()) {
System.out.println(table.getName());
}
// 篩選表格
ListTablesOptions options = new ListTablesOptions()
.setFilter("TableName eq 'mytable'");
for (TableItem table : serviceClient.listTables(options, null, null)) {
System.out.println(table.getName());
}
刪除資料表
serviceClient.deleteTable("mytable");
類型化實體
public class Product implements TableEntity {
private String partitionKey;
private String rowKey;
private OffsetDateTime timestamp;
private String eTag;
private String name;
private double price;
// 所有欄位的存取器與設定器
@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; }
// ... 其他存取器/設定器
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; }
}
// 使用範例
Product product = new Product();
product.setPartitionKey("electronics");
product.setRowKey("laptop-001");
product.setName("Laptop");
product.setPrice(999.99);
tableClient.createEntity(product);
錯誤處理
import com.azure.data.tables.models.TableServiceException;
try {
tableClient.createEntity(entity);
} catch (TableServiceException e) {
System.out.println("狀態: " + e.getResponse().getStatusCode());
System.out.println("錯誤: " + e.getMessage());
// 409 = 衝突(實體已存在)
// 404 = 未找到
}
環境變數
# 儲存帳戶
AZURE_TABLES_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=... # Entra ID 驗證的替代方案
AZURE_TABLES_ENDPOINT=https://.table.core.windows.net # 所有驗證方法皆需此設定
AZURE_TOKEN_CREDENTIALS=prod # 僅當在生產環境中使用 DefaultAzureCredential 時才需要
# Cosmos DB 表格 API
COSMOS_TABLE_ENDPOINT=https://.table.cosmosdb.azure.com # Cosmos DB 表格 API 的替代端點
最佳實務
- 分區鍵設計:選擇能均勻分佈負載的鍵
- 批次操作:使用交易來執行原子性的多實體更新
- 查詢優化:盡可能透過 PartitionKey 進行篩選
- 選取投影:為提升效能,僅選取所需的屬性
- 實體大小:將實體大小控制在 1MB(Storage)或 2MB(Cosmos)以下
觸發詞
- 「Azure Tables Java」
- 「表儲存 SDK」
- 「Cosmos DB Table API」
- 「NoSQL 鍵值儲存」
- 「分區鍵、列鍵」
- 「表格實體 CRUD」
---
name: azure-data-tables-java
description: Build table storage applications using the Azure Tables SDK for Java, supporting both Azure Table Storage and Cosmos DB Table API for NoSQL key-value data.
license: MIT
---
# 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.
## Installation
```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();
```
### 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();
```
### With SAS Token
```java
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.sasToken("<sas-token>")
.buildClient();
```
### With DefaultAzureCredential (Storage only)
```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
TableServiceClient serviceClient = new TableServiceClientBuilder()
.endpoint("<your-table-account-url>")
.credential(credential)
.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)
## 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");
```
### Get Table Client
```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);
```
### 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);
```
### 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);
```
### Upsert Entity
```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");
```
### 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"));
}
```
### Query with OData Filter
```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);
```
### 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());
}
```
### Delete Table
```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);
```
## 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
}
```
## Environment Variables
```bash
# Storage Account
AZURE_TABLES_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=... # Alternative to Entra ID auth
AZURE_TABLES_ENDPOINT=https://<account>.table.core.windows.net # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
# Cosmos DB Table API
COSMOS_TABLE_ENDPOINT=https://<account>.table.cosmosdb.azure.com # Alternative endpoint for Cosmos DB Table API
```
## Best Practices
1. **Partition Key Design**: Choose keys that distribute load evenly
2. **Batch Operations**: Use transactions for atomic multi-entity updates
3. **Query Optimization**: Always filter by PartitionKey when possible
4. **Select Projection**: Only select needed properties for performance
5. **Entity Size**: Keep entities under 1MB (Storage) or 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"
所有檔案
0 個檔案安裝 azure-data-tables-java
請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-data-tables-java # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
