Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDBMapper load cannot instantiate Kotlin data class

Using DynamoDBMapper within an AWS Lambda (i.e. not Android) written in Kotlin, I can save a record using a data class. However when I attempt to load a record to a data class, I receive a "DynamoDBMappingException: could not instantiate class" exception.

@DynamoDBTable(tableName = "Test")
data class TestItem(
    @DynamoDBHashKey(attributeName="someKey")
    @DynamoDBAttribute(attributeName = "someKey")
    var someKey: String?,

    @DynamoDBAttribute(attributeName = "someValue")
    var someValue: String?
}

val ddbMapper = DynamoDBMapper(AmazonDynamoDBClientBuilder.defaultClient())
ddbMapper.load(TestItem::class.java, "xyz")

Results in the following exception:

com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: could not instantiate class com.intuit.connect_to_pro.lambda_common_core.aws_service.TestItem

With the root exception being:

java.lang.NoSuchMethodException: com.intuit.connect_to_pro.lambda_common_core.aws_service.TestItem.()

AWS has an example for Android that uses com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper instead of com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper. I tried the Android version, but the result was the same.

https://docs.aws.amazon.com/aws-mobile/latest/developerguide/add-aws-mobile-nosql-database.html

Any help would be appreciated.

like image 516
Ken Avatar asked Jun 28 '18 00:06

Ken


1 Answers

The DynamoDBMapper expects a class with an empty constructor. Using a Kotlin data class, you can specify default values for all parameters and use @JvmOverload, which will generate the empty constructor for JVM (Java). Also all parameters need to be mutable, so you need to use "var" instead of "val".

@DynamoDBTable(tableName = "Test")
data class TestItem @JvmOverloads constructor(

   @DynamoDBHashKey(attributeName="someKey")
   var someKey: String = "",

   var someValue: String = ""
)
like image 57
Ken Avatar answered Oct 02 '22 21:10

Ken