1
votes

I am trying to save datetime as Date to dynamoDB but for some reason it is being saved as string. I checked on the documentation and Date is a supported datatype. Because of this, when I am trying to scan my table, I am getting an error saying time cannot be unconverted

public class func{
private static final Logger LOGGER = LoggerFactory.getLogger(func.class);
    private AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.defaultClient();
    DynamoDBMapper mapper =new DynamoDBMapper(dynamoDB);


private boolean addData(MyClass myClass){
        try{
            mapper.save(MyClass);
            return true;
        } catch (Exception ex) {
                LOGGER.error("error: {}", ex.getMessage());
        }
        return false;
    }


public List<MyClass> getAll() {
        List<MyClass>  list = new ArrayList<>();
        try{
            list = mapper.scan(MyClass.class, new DynamoDBScanExpression());
            return list;
        }catch (Exception ex){
            LOGGER.error("Fetching error: {}", ex.getMessage());
        }
        return list;
    }
}

@DynamoDBTable(tableName = "table")
public class MyClass {
    @DynamoDBHashKey(attributeName="id")
    public String id;

    @DynamoDBAttribute(attributeName="create_time")
    public Date createTime;
    public void setCreateTime(Date createTime){ this.createTime = createTime;}
    public Date getCreateTime(){ return this.createTime; }
}

OOPS: Sorry. Forgot to read entire document. Seems like Date is of String type https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.DataTypes.html

How can I overcome the error when I am trying to scan through the table?

1

1 Answers

0
votes

You already linked to the relevant docs:

Java type DynamoDB type
All number types N (number type)
Strings S (string type)
Boolean BOOL (Boolean type), 0 or 1.
ByteBuffer B (binary type)
Date S (string type). The Date values are stored as ISO-8601 formatted strings.
Set collection types SS (string set) type, NS (number set) type, or BS (binary set) type.

Java Dates are mapped to a string type in DynamoDB. This happens for the simple reason that DynamoDB doesn't support Datetime information as a separate datatype.

There's two common ways to encode datetime information in DynamoDB:

  • save it as an ISO8601 formatted string, e.g. 2021-02-22T09:58:00.000+01:00
  • save it as a Number in Unix/Epoch format, e.g. 1613984280

The mapper chooses the former representation, presumably because it's human readable.