Basics of Using DynamoDB with Java
December 01, 2020
WIP: open questions, lessons learned, tips, etc. from working with DynamoDB in Java.
Different SDKs
Below are the official SDKs and clients available for Java. Beware of different SDKs especially when researching issues, e.g. before digging into documentation, check which SDK or which version it is for.
-
AWS SDK for Java v2
-
Enhanced Client for v2 SDK
-
AWS SDK for Java v1
-
DynamoDBMapper for v1 SDK
Watch out for transactional operations as well. They have their own classes, like Get
and Put
Just as with Java, NodeJS and Python have older, lower-level SDKs which require you
to write DynamoDB JSON, like {'Name': {'S': 'Jack}}
, and newer SDKs which take
care of the datatype “wrapping” for you so you can just write: {'Name': 'Jack'}
AWS SDK v2 Java
Feature Requests
Open
-
DynamoDB Enhanced Client: Provide JSON Attribute Converter Out of the Box
- Working on this myself
-
Enhanced DynamoDB annotations are incompatible with Lombok
- Specifically, I added onto this feature request to support derived fields on immutable value class entities
Resolved
-
DynamoDB Enhanced Client: Support Querying and Marshalling Heterogeneous Item Collections
- Once I understand the SDK codebase better, I would ideally like to contribute this myself
- See how to do this here:
Questions and Answers
How is UpdateItem
handled if no existing item matches the supplied Key
?
Answer: A new item is created with the supplied key and the update supplied in the UpdateExpression
.
Example
Start with an empty table
PK | SK | UserName |
---|---|---|
…and run this:
aws dynamodb
--table MyTable
--key '{"PK": {"S": "ORDER#123"}, "SK": {"S": "A"}}'
--update-expression "set UserName = :username"
--expression-attribute-values = '{":username": {"S": "User123"}}'
This will result in a new item being created:
PK | SK | UserName |
---|---|---|
ORDER#123 | A | User123 |
To prevent this you must add a ConditionExpression
which will result in a
condition check failure if no item matches the provided Key
(and therefore no PK
attribute exists for that Key
):
--condition-expression "attribute_exists(PK)"