Search code examples
javatimelocaldatetime

LocalDateTime precision issue rig my equals and hashCode methods


I have auditing fields as LocalDateTime type in my model.

I also use Lombok for equals and hashCode implementations.

Between persist (with ID) and fetch (by ID), precision is loosed.


I went ahead and truncated to seconds (then milliseconds) before marshalling and after unmarshalling the entity to and fro the persistent layer (DB driver)... But it seems there is more to it.

At the end, I implemented those methods in my base entities by hand (as opp. to using Lombok) and truncated LocaDateTime in there.

QUESTION: How to set LocalDateTime precision globally (system, spring-context or maybe else)?


Solution

  • Clock

    You can optionally supply an alternate Clock to the java.time classes.

    In your case, you want Clock.tickSeconds. To quote the Javadoc:

    Obtains a clock that returns the current instant ticking in whole seconds using the best available system clock.

    For example, to capture the current moment as seen with an offset-from-UTC of zero hours-minutes-seconds truncated to whole seconds:

    Instant instant = Instant.now( Clock.tickSeconds() ) ;