Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB mapping List of Enum

Mapping an enum class in to DynamoDB object is really simple by using Custom Marshall. But how to map a List of Enum?

Enum class

public enum Transport {
SMS,EMAIL,ALL;
}

DynamoDB mapper

public class Campaign{
   private List<Transport> transport;

   @DynamoDBAttribute(attributeName = "transport")
   public List<Transport> getTransport() {
       return transport;
   }

   public void setTransport(List<Transport> transport) {
      this.transport = transport;
   }
}
like image 736
Madura Pradeep Avatar asked Apr 08 '16 09:04

Madura Pradeep


2 Answers

DynamoDBMarshaller is deprecated. Use DynamoDBTypeConverter instead.

Example:

Enum class

public static enum ValidationFailure {
    FRAUD, GENERAL_ERROR
}

DynamoDBTable class

 @DynamoDBTable(tableName = "receipt")
public class Receipt {

    private Long id;
    private List<ValidationFailure> validation;

    @DynamoDBHashKey(attributeName = "id")
    public Long getId() {
        return id;
    }

    @DynamoDBTypeConverted(converter = ValidationConverter.class)
    public List<ValidationFailure> getValidation() {
        return validation;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setValidation(List<ValidationFailure> validation) {
        this.validation = validation;
    }
}

Convertor:

public class ValidationConverter implements DynamoDBTypeConverter<List<String>, List<ValidationFailure>> {

@Override
public List<String> convert(List<ValidationFailure> object) {
    List<String> result = new ArrayList<String>();
    if (object != null) {
        object.stream().forEach(e -> result.add(e.name()));
    }
    return result;
}

@Override
public List<ValidationFailure> unconvert(List<String> object) {
    List<ValidationFailure> result = new ArrayList<ValidationFailure>();
    if (object != null) {
        object.stream().forEach(e -> result.add(ValidationFailure.valueOf(e)));
    }
    return result;
}
}
like image 198
shimiA Avatar answered Oct 07 '22 02:10

shimiA


It's working for me, I have used the Set

@DynamoDBTyped(DynamoDBMapperFieldModel.DynamoDBAttributeType.SS)
var roles: MutableSet<Employee.Role>? = null

I think the same approach would work for List with DynamoDBAttributeType.L

like image 37
Viacheslav Petriaiev Avatar answered Oct 07 '22 02:10

Viacheslav Petriaiev