Created
January 19, 2018 05:41
-
-
Save user454322/8bdd359556629ec294cb9b41cbc6ff3b to your computer and use it in GitHub Desktop.
Store ZonedDateTimeConverter as timestamp using JPA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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