How to correctly set the type dateTime to a predicate from Java

In an application written in Java using the JavaSDK for DGraph, we want to add Date information to certain nodes.
Intuitively, one would group a node as a class and add one of the various java.time classes as a field.
However, it is not clear which class should be used in order for dgraph to accept the value.

As a deserializer, I am using Jackson, since its support for unwrapping Single Element Arrays to a Single Element in an object, is very convenient.
Do I have to tell Jackson on how to correctly serialize the date object?
Or is there some date object that can be serialized without further effort?

In my research for the answer, I tried several date and time classes and discovered the following:

  • java.util.Date: When using this class, neither dgraph nor Jackson complains and executes happily the mutation. However, in the database, it seems so that the predicate is not set at all. Moreover, java.util.Date's methods are almost all deprecated, so it shouldn’t be used anyways.

  • java.time.LocalDate and java.time.LocalDateTime: Dgraph complains about these types, because Jackson serializes them to have several fields.

{
    "createdAt": { 
        "nano":80013400,
        "year":2018,
        "monthValue":3,
        "dayOfMonth":13,
        "hour":13,
        "minute":26,
        "second":0,
        "month":"MARCH",
        "dayOfWeek":"TUESDAY",
        "dayOfYear":72,
        "chronology": {
            "id":"ISO",
            "calendarType":"iso8601"
        }
    },
    "createdBy":"John Doe"
}

Obviously, not the result we desire.

After some research, I found the jackson module jackson-datatype-jsr310 which adds better serialization support for Dates in java.
After enabling the module for the ObjectMapper via

ObjectMapper objMapper = new ObjectMapper()
        ...
        .registerModule(new JavaTimeModule());

we receive the following json serialization:

{
    "createdAt":[2018,3,13,13,24,40,171731300],
    "createdBy":"John Doe"
}

Still not quite the resut we desire, although DGraph accepts this mutation, but the Dates are not correct.
Thus, we need to add an additional feature to the ObjectMapper:

ObjectMapper objMapper = new ObjectMapper()
        ...
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .registerModule(new JavaTimeModule());

Now the result is as expected and we can commit mutations with java.time.LocalDateTime.

{
     "createdAt":"2018-03-13T13:35:16.1354711",
     "createdBy":"John Doe"
}
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.