'DynamoDB Composite PK with UUID
I have an issue with UUID when it is used in my PK in DynamoDB in the format
PK :EXAMPLE#{someUUID}
I am generating a UUID using the @DynamoDBAutoGeneratedKey annotation in springboot which generates the UUID in my field but is however, not present in my PK.
My model implementation:
public class ExampleClass {
@DynamoDBHashKey(attributeName = "PK")
public String getPK() {
return "EXAMPLE" + someUUID;
}
@DynamoDBAttribute
@DynamoDBAutoGeneratedKey
private String someUUID;
}
My results when I insert a record using DynamoDBMapper.save inserts the records with all the attributes but with:
PK : EXAMPLE#null
Programmically creating the UUID before insert fixes the problem, however I have to generate the UUID manually before every insert which isn't ideal.
Is there any way to populate getPK() while using DynamoDBAutoGeneratedKey?
Solution 1:[1]
My implamatation for this context:
1º - Create one anotation:
package io.github.wesleyosantos91.api.anotation;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGenerateStrategy;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGenerated;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.UUID;
@DynamoDBAutoGenerated(generator=CustomGeneratedKey.Generator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CustomGeneratedKey {
String prefix() default "";
public static class Generator implements DynamoDBAutoGenerator<String> {
private final String prefix;
public Generator(final Class<String> targetType, final CustomGeneratedKey annotation) {
this.prefix = annotation.prefix();
}
public Generator() {
this.prefix = "";
}
@Override
public DynamoDBAutoGenerateStrategy getGenerateStrategy() {
return DynamoDBAutoGenerateStrategy.CREATE;
}
@Override
public final String generate(final String currentValue) {
return prefix + UUID.randomUUID();
}
}
}
2º - Add anotation in atribute with desired prefix:
@DynamoDBHashKey
@CustomGeneratedKey(prefix="PERSON#")
private String id;
Result
PERSON#43bcad81-7bad-4c5f-ad55-dc26ced3c3ef
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wesleyosantos91 |
