azure-data-tables-java
microsoft/skills
Azure Tables SDK for Java を使用して、NoSQL キーバリューデータ向けの Azure Table Storage および Cosmos DB Table API の両方をサポートするテーブルストレージアプリケーションを構築します。
...すべて拡張しますJava用 Azure Tables SDK
Azure Tables SDK for Java を使用して、テーブル ストレージ アプリケーションを構築します。Azure Table Storage と Cosmos DB Table 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 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);
エンティティの更新
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("Quantity", 150);
tableClient.updateEntity(replaceEntity, TableEntityUpdateMode.REPLACE);
エンティティのアップサート
// 挿入または更新(マージモード)
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 Table API
COSMOS_TABLE_ENDPOINT=https://.table.cosmosdb.azure.com # Cosmos DB Table API の代替エンドポイント
ベストプラクティス
- パーティションキーの設計:負荷を均等に分散させるキーを選択する
- バッチ処理: 複数のエンティティに対するアトミックな更新にはトランザクションを使用する
- クエリの最適化: 可能な場合は常に PartitionKey によるフィルタリングを行う
- 選択プロジェクション: パフォーマンス向上のため、必要なプロパティのみを選択する
- エンティティのサイズ:エンティティのサイズを1MB(Storage)または2MB(Cosmos)未満に抑える
トリガーフレーズ
- 「Azure Tables Java」
- 「Table Storage 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
コピー





家
