I'm utilizing java.time.LocalDateTime in my java application. I'm also trying to use DynamoDBMapper
and via the annotation save the LocalDateTime
variable. Unfortunately I get the following error:
DynamoDBMappingException: Unsupported type: class java.time.LocalDateTime
Is there a way to have this mapping without using DynamoDBMarshalling
?
You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.
The DynamoDBMapper class enables you to access your tables; perform various create, read, update, and delete (CRUD) operations; and run queries. The DynamoDBMapper class does not allow you to create, update, or delete tables. To perform those tasks, use the low-level SDK for Java interface instead.
LocalDateTime is an immutable date-time object that represents a date-time with default format as yyyy-MM-dd-HH-mm-ss.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision.
No AWS DynamoDB Java SDK can't map java.time.LocalDateTime natively without using any annotation.
To do this mapping, you have to use DynamoDBTypeConverted
annotation introduced in the version 1.11.20 of the AWS Java SDK. Since this version, the annotation DynamoDBMarshalling
is deprecated.
You can do that like this:
class MyClass {
...
@DynamoDBTypeConverted( converter = LocalDateTimeConverter.class )
public LocalDateTime getStartTime() {
return startTime;
}
...
static public class LocalDateTimeConverter implements DynamoDBTypeConverter<String, LocalDateTime> {
@Override
public String convert( final LocalDateTime time ) {
return time.toString();
}
@Override
public LocalDateTime unconvert( final String stringValue ) {
return LocalDateTime.parse(stringValue);
}
}
}
With this code, the stored dates are saved as string in the ISO-8601 format like that: 2016-10-20T16:26:47.299
.
Despite what I said I found it simple enough to use DynamoDBMarshalling
to marshal to and from a string. Here is my code snippet and an AWS reference:
class MyClass {
...
@DynamoDBMarshalling(marshallerClass = LocalDateTimeConverter.class)
public LocalDateTime getStartTime() {
return startTime;
}
...
static public class LocalDateTimeConverter implements DynamoDBMarshaller<LocalDateTime> {
@Override
public String marshall(LocalDateTime time) {
return time.toString();
}
@Override
public LocalDateTime unmarshall(Class<LocalDateTime> dimensionType, String stringValue) {
return LocalDateTime.parse(stringValue);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With