Amazon DynamoDB
开发人员指南 (API Version 2012-08-10)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。请点击 Amazon AWS 入门,可查看中国地区的具体差异

对象持久化接口

一些 AWS 开发工具包提供一个对象持久化接口,在该接口中不直接执行数据层面的操作,而是创建对象来表示 DynamoDB 表和索引中的项目,并且仅与这些对象进行交互。这样,您就可以编写以对象为中心的代码,而不是编写以数据库为中心的代码。

注意

对象持久化接口在适用于 Java 和 .NET 的 AWS 开发工具包中可用。有关更多信息,请参阅 DynamoDB 的高级编程接口

下面的 Java 程序使用AWS SDK for Java的对象持久化接口 DynamoDBMapperMusicItem 类表示 Music 表中的项目。

Copy
package com.amazonaws.codesamples; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; @DynamoDBTable(tableName="Music") public class MusicItem { private String artist; private String songTitle; private String albumTitle; private int year; @DynamoDBHashKey(attributeName="Artist") public String getArtist() { return artist;} public void setArtist(String artist) {this.artist = artist;} @DynamoDBRangeKey(attributeName="SongTitle") public String getSongTitle() { return songTitle;} public void setSongTitle(String songTitle) {this.songTitle = songTitle;} @DynamoDBAttribute(attributeName = "AlbumTitle") public String getAlbumTitle() { return albumTitle;} public void setAlbumTitle(String albumTitle) {this.albumTitle = albumTitle;} @DynamoDBAttribute(attributeName = "Year") public int getYear() { return year; } public void setYear(int year) { this.year = year; } }

然后,您可以实例化 MusicItem 对象,并使用 DynamoDBMapperload() 方法检索歌曲。该程序随后输出歌曲发行年份。

com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper 类实现了该 DynamoDB 对象持久化接口。请注意 DynamoDBMapper 如何用作一个围绕低级别客户端 (AmazonDynamoDB) 的包装程序。

Copy
package com.amazonaws.codesamples; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; public class MusicMapperDemo { public static void main(String[] args) { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDBMapper mapper = new DynamoDBMapper(client); MusicItem keySchema = new MusicItem(); keySchema.setArtist("No One You Know"); keySchema.setSongTitle("Call Me Today"); try { MusicItem result = mapper.load(keySchema); if (result != null) { System.out.println( "The song was released in "+ result.getYear()); } else { System.out.println("No matching song was found"); } } catch (Exception e) { System.err.println("Unable to retrieve data: "); System.err.println(e.getMessage()); } } }