omnifaces / omnipersistence

Utilities for JPA, JDBC and DataSources
Other
31 stars 12 forks source link

AttributeConverter for TimestampedEntity #9

Closed mydeadlyvenoms closed 6 years ago

mydeadlyvenoms commented 6 years ago

Maybe I did something wrong but I wasn't able to map Instant to Timestamp OR DateTime when using TimestampedEntity. To make it work I had to implement the following AttributeConverter. Did I miss something or is this the way to go?

@Converter(autoApply = true)
public class InstantTimestampAttributeConverter implements AttributeConverter<Instant, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(Instant attribute) {
        return Timestamp.from(attribute);
    }

    @Override
    public Instant convertToEntityAttribute(Timestamp dbData) {
        return dbData.toInstant();
    }

}
BalusC commented 6 years ago

java.time API is only natively supported since JPA 2.2 (Hibernate 5.2+, EclipseLink 2.7+).

Otherwise, you indeed need an attribute converter.

mydeadlyvenoms commented 6 years ago

Thank you for your response, makes sense. :-) Can't we add the AttributeConverter for backward compatibility?

mydeadlyvenoms commented 6 years ago

Hi @BalusC After migrating to Java EE 8 using Payara 5.181 (and Eclipselink as its JPA 2.2 implementation) the following Converter is still required. Instant is not covered by JPA 2.2, I guess you tested it using Hibernate (which has an additional feature to map it). Or am I completely missing something?

@Converter(autoApply = true)
public class InstantAttributeConverter implements AttributeConverter<Instant, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(Instant instant) {
        return instant == null ? null : Timestamp.from(instant);
    }

    @Override
    public Instant convertToEntityAttribute(Timestamp timestamp) {
        return timestamp == null ? null : timestamp.toInstant();
    }

}
mydeadlyvenoms commented 6 years ago

Of course I can provide a Pull-Request if you like, but I am not sure if this is the way you like to go. Maybe it is a cleaner solution to not Instant.

BalusC commented 6 years ago

You're right, in the end, support for java.time.Instant was actually not implemented: https://github.com/javaee/jpa-spec/issues/63

You'll have to use this converter for now.