如何在Scala中使用亚马逊的DynamoDBMapper?

eld*_*bra 8 scala amazon-web-services amazon-dynamodb

我在Scala代码中使用Amazon的DynamoDBMapper时遇到了麻烦.主要的关键点是让JVM在案例类中使用时识别@DynamoDBHashkey,例如:

case class MyCoolCaseClass(@DynamoDBHashKey(attributeName = "my_id") myId: String) {}

将此客户端库集成到Scala项目中的人的任何指示?(我希望不要简单地回到低级API,尽管这可能是一个不错的决定,一旦用Mapper耗尽我的选择).

Mat*_*ttE 10

DynamoDB映射器使用反射来查找getter和setter.SDK采用Java风格的约定,即getter和setter以"get"或"is"开头,setter以"set"开头.你可以在github上看到反射代码.

我已经能够让它工作,但感觉就像写Java :(

@DynamoDBTable(tableName = "awesome_table")
class TheBestClass {
  private var id : Integer = _

  @DynamoDBHashKey
  def getId() = id
  def setId(_id: Integer) = id = _id
}
Run Code Online (Sandbox Code Playgroud)


qu1*_*0t3 10

我不得不这样做:

import annotation.meta.beanGetter
import beans.BeanProperty

import com.amazonaws.services.dynamodbv2.datamodeling._

@DynamoDBTable(tableName="DEMOTAB")
case class DemoItem(  // it's a case class for the free stuff, but can be ordinary class
    @(DynamoDBHashKey @beanGetter)  // would not work without meta annotation
    @BeanProperty var id:String,    // must be var or mapper can't instantiate one

    @BeanProperty var number:Integer
) {
  def this() = this(null, null)     // needed by DynamoDB Mapper to instantiate
}
Run Code Online (Sandbox Code Playgroud)

  • @BeanProperty是与任何希望遵循JavaBeans约定的反射库交互的"官方"方式. (3认同)