Skip to content

Instantly share code, notes, and snippets.

@codecitizen
Created November 15, 2016 15:28
Show Gist options
  • Save codecitizen/e78865f68e9fd727c3e2ccb591ffe430 to your computer and use it in GitHub Desktop.
Save codecitizen/e78865f68e9fd727c3e2ccb591ffe430 to your computer and use it in GitHub Desktop.
JPA Attribute Converter for java.time.LocalDateTime to java.sql.Instant
package com.github.gist.codecitizen.jpa.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.LocalDateTime;
/**
* Maps {@link java.time.LocalDateTime} entity attributes to {@link java.sql.Timestamp} values
* so a temporal value instead of {@code bytea} is written to the database.
*
* @author codecitizen (Github)
*/
@SuppressWarnings(value = "unused")
@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime attribute) {
return (attribute == null)? null : Timestamp.valueOf(attribute);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp dbData) {
return (dbData == null) ? null : dbData.toLocalDateTime();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment