对象持久化接口 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

对象持久化接口

如果不直接执行数据层面操作,一些 Amazon SDK 提供对象持久化接口。相反,您可以创建表示 Amazon DynamoDB 表和索引中项目的对象,并且仅与这些对象进行交互。这允许您编写以对象为中心的代码,而不是以数据库为中心的代码。

注意

适用于 Java 和 .NET 的 Amazon SDK 提供对象持久化接口。有关更多信息,请参阅 DynamoDB 的

以下 Java 程序使用 DynamoDBMapper,Amazon SDK for Java 的对象持久化接口。MusicItem 类表示 Music 表的项目。

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)。

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()); } } }