对象持久化接口 - Amazon DynamoDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

对象持久化接口

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

注意

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

以下 Java 程序使用DynamoDBMapper,对象持久化接口AWS 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对象,然后使用load()的方法DynamoDBMapper。然后,该程序打印该歌曲的发行年份。

这些区域有: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()); } } }