azure-data-tables-java
microsoft/skills
Java용 Azure Tables SDK를 사용하여 Azure Table Storage와 NoSQL 키-값 데이터를 위한 Cosmos DB Table API를 모두 지원하는 테이블 스토리지 애플리케이션을 구축하세요.
...모든 것을 확장하십시오Java용 Azure Tables SDK
Java용 Azure 테이블 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)
- 파티션 키: 효율적인 쿼리를 위해 엔티티를 그룹화
- 행 키(Row Key): 파티션 내의 고유 식별자
- 엔티티: 최대 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("제품: %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);
// Replace (엔티티 전체 교체)
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 테이블 API
COSMOS_TABLE_ENDPOINT=https://.table.cosmosdb.azure.com # Cosmos DB 테이블 API용 대체 엔드포인트
모범 사례
- 파티션 키 설계: 부하를 균등하게 분산시키는 키를 선택하십시오
- 일괄 작업: 원자적인 다중 엔티티 업데이트를 위해 트랜잭션을 사용하십시오
- 쿼리 최적화: 가능한 경우 항상 PartitionKey로 필터링하십시오
- 선택적 투영: 성능 향상을 위해 필요한 속성만 선택하십시오
- 엔티티 크기: 엔티티 크기를 1MB(Storage) 또는 2MB(Cosmos) 미만으로 유지하십시오
트리거 문구
- "Azure Tables Java"
- "테이블 스토리지 SDK"
- "Cosmos DB 테이블 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
복사





집
