AWS SDK for Java 1.x는 2024년 7월 31일부터 유지 관리 모드로 전환되었으며 2025년 12월 31일에 지원 종료
DynamoDB에서의 항목 작업
DynamoDB에서 항목은 각각 이름과 값이 있는 속성의 컬렉션입니다. 속성 값은 스칼라, 세트 또는 문서 유형일 수 있습니다. 자세한 정보는 Amazon DynamoDB 개발자 안내서의 명명 규칙과 데이터 유형을 참조하세요.
테이블에서 항목 검색(가져오기)
AmazonDynamoDB의 getItem의 메서드를 호출하여 테이블 이름과 원하는 항목의 기본 키 값이 포함된 GetItemRequest 객체를 이 메서드에 전달합니다. 이 메서드는 GetItemResult 객체를 반환합니다.
반환된 GetItemResult 객체의 getItem() 메서드를 사용하여 항목과 연결된 키 (문자열) 및 값 (AttributeValue) 쌍의 맵
가져옵니다.
import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; import java.util.HashMap; import java.util.Map;
코드
HashMap<String,AttributeValue> key_to_get = new HashMap<String,AttributeValue>(); key_to_get.put("DATABASE_NAME", new AttributeValue(name)); GetItemRequest request = null; if (projection_expression != null) { request = new GetItemRequest() .withKey(key_to_get) .withTableName(table_name) .withProjectionExpression(projection_expression); } else { request = new GetItemRequest() .withKey(key_to_get) .withTableName(table_name); } final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); try { Map<String,AttributeValue> returned_item = ddb.getItem(request).getItem(); if (returned_item != null) { Set<String> keys = returned_item.keySet(); for (String key : keys) { System.out.format("%s: %s\n", key, returned_item.get(key).toString()); } } else { System.out.format("No item found with the key %s!\n", name); } } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1);
GitHub의 전체 예제
테이블에 새 항목 추가
항목의 속성을 나타내는 키-값 페어의 맵
참고
계정 및 리전에 대해 이름이 지정된 테이블이 없으면 ResourceNotFoundException이 발생합니다.
가져옵니다.
import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import java.util.ArrayList;
코드
HashMap<String,AttributeValue> item_values = new HashMap<String,AttributeValue>(); item_values.put("Name", new AttributeValue(name)); for (String[] field : extra_fields) { item_values.put(field[0], new AttributeValue(field[1])); } final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); try { ddb.putItem(table_name, item_values); } catch (ResourceNotFoundException e) { System.err.format("Error: The table \"%s\" can't be found.\n", table_name); System.err.println("Be sure that it exists and that you've typed its name correctly!"); System.exit(1); } catch (AmazonServiceException e) { System.err.println(e.getMessage()); System.exit(1);
GitHub의 전체 예제
테이블의 기존 항목 업데이트
AmazonDynamoDB의 updateItem 메서드를 사용하여 테이블 이름, 기본 키 값 및 업데이트할 필드 맵을 지정함으로써 테이블에 이미 존재하는 항목의 속성을 업데이트할 수 있습니다.
참고
해당 계정 및 리전에 대해 이름이 지정된 테이블이 없거나 전달한 기본 키로 식별되는 항목이 없으면 ResourceNotFoundException이 발생합니다.
가져옵니다.
import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeAction; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import java.util.ArrayList;
코드
HashMap<String,AttributeValue> item_key = new HashMap<String,AttributeValue>(); item_key.put("Name", new AttributeValue(name)); HashMap<String,AttributeValueUpdate> updated_values = new HashMap<String,AttributeValueUpdate>(); for (String[] field : extra_fields) { updated_values.put(field[0], new AttributeValueUpdate( new AttributeValue(field[1]), AttributeAction.PUT)); } final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); try { ddb.updateItem(table_name, item_key, updated_values); } catch (ResourceNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } catch (AmazonServiceException e) { System.err.println(e.getMessage()); System.exit(1);
GitHub의 전체 예제
DynamoDBMapper 클래스 사용
AWS SDK for Java
참고
DynamoDBMapper 클래스는 테이블 생성, 업데이트 또는 삭제를 허용하지 않습니다.
가져옵니다.
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException;
코드
다음 자바 코드 예제는 DynamoDBMapper 클래스를 사용하여 Music 테이블에 콘텐츠를 추가하는 방법을 보여줍니다. 테이블에 콘텐츠가 추가되면 파티션 및 정렬 키를 사용하여 항목이 로드됩니다. 그런 다음 수상 항목이 업데이트됩니다. Music 테이블을 생성하는 방법에 대한 자세한 내용은 Amazon DynamoDB 개발자 안내서의 테이블 생성을 참조하세요.
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); MusicItems items = new MusicItems(); try{ // Add new content to the Music table items.setArtist(artist); items.setSongTitle(songTitle); items.setAlbumTitle(albumTitle); items.setAwards(Integer.parseInt(awards)); //convert to an int // Save the item DynamoDBMapper mapper = new DynamoDBMapper(client); mapper.save(items); // Load an item based on the Partition Key and Sort Key // Both values need to be passed to the mapper.load method String artistName = artist; String songQueryTitle = songTitle; // Retrieve the item MusicItems itemRetrieved = mapper.load(MusicItems.class, artistName, songQueryTitle); System.out.println("Item retrieved:"); System.out.println(itemRetrieved); // Modify the Award value itemRetrieved.setAwards(2); mapper.save(itemRetrieved); System.out.println("Item updated:"); System.out.println(itemRetrieved); System.out.print("Done"); } catch (AmazonDynamoDBException e) { e.getStackTrace(); } } @DynamoDBTable(tableName="Music") public static class MusicItems { //Set up Data Members that correspond to columns in the Music table private String artist; private String songTitle; private String albumTitle; private int awards; @DynamoDBHashKey(attributeName="Artist") public String getArtist() { return this.artist; } public void setArtist(String artist) { this.artist = artist; } @DynamoDBRangeKey(attributeName="SongTitle") public String getSongTitle() { return this.songTitle; } public void setSongTitle(String title) { this.songTitle = title; } @DynamoDBAttribute(attributeName="AlbumTitle") public String getAlbumTitle() { return this.albumTitle; } public void setAlbumTitle(String title) { this.albumTitle = title; } @DynamoDBAttribute(attributeName="Awards") public int getAwards() { return this.awards; } public void setAwards(int awards) { this.awards = awards; } }
GitHub의 전체 예제
추가 정보
-
Amazon DynamoDB 개발자 안내서의 항목 작업 가이드라인
-
Amazon DynamoDB 개발자 안내서의 DynamoDB의 항목 작업 가이드라인