Skip to content

Instantly share code, notes, and snippets.

@user454322
Created January 19, 2018 05:41
Show Gist options
  • Save user454322/8bdd359556629ec294cb9b41cbc6ff3b to your computer and use it in GitHub Desktop.
Save user454322/8bdd359556629ec294cb9b41cbc6ff3b to your computer and use it in GitHub Desktop.
Store ZonedDateTimeConverter as timestamp using JPA
/*
* Store Java 8 ZonedDateTimeConverter as Timestamp in the database.
* Set `hibernate.jdbc.time_zone = UTC` so the timezone is set to UTC.
*/
package info.modprobe.cwp.data;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import static java.util.Optional.ofNullable;
@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, java.sql.Timestamp> {
@Override
public java.sql.Timestamp convertToDatabaseColumn(final ZonedDateTime entityValue) {
return ofNullable(entityValue)
.map(entityTime -> entityTime.toInstant())
.map(java.sql.Timestamp::from)
.orElse(null);
}
@Override
public ZonedDateTime convertToEntityAttribute(final java.sql.Timestamp databaseValue) {
return ofNullable(databaseValue)
.map(databaseTime -> databaseTime.toLocalDateTime())
.map(localDateTime -> localDateTime.atZone(ZoneId.of("UTC")))
.orElse(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment