Implemented and Instant-to-Date converter
authorKai Moritz <kai@juplo.de>
Mon, 21 Dec 2015 19:55:08 +0000 (20:55 +0100)
committerKai Moritz <kai@juplo.de>
Tue, 22 Dec 2015 09:54:24 +0000 (10:54 +0100)
src/main/java/de/juplo/jpa/converters/InstantConverter.java [new file with mode: 0644]

diff --git a/src/main/java/de/juplo/jpa/converters/InstantConverter.java b/src/main/java/de/juplo/jpa/converters/InstantConverter.java
new file mode 100644 (file)
index 0000000..fe6bbd6
--- /dev/null
@@ -0,0 +1,33 @@
+package de.juplo.jpa.converters;
+
+import java.time.Instant;
+import java.util.Date;
+import javax.persistence.AttributeConverter;
+import javax.persistence.Converter;
+
+
+/**
+ * Converts an {@link Instant} to a {@link Date}, as suggested in
+ * the official Java 8 Time tutorial.
+ * <p>
+ * The {@link Date} can then be persisted as
+ * {@link java.persistene.TemporalType.TIMESTAMP} with the help of the
+ * {@link java.persist.Tmporal}-annotation.
+ * @see https://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html
+ * @author Kai Moritz
+ */
+@Converter(autoApply = true)
+public class InstantConverter implements AttributeConverter<Instant, Date>
+{
+  @Override
+  public Date convertToDatabaseColumn(Instant instant)
+  {
+    return Date.from(instant);
+  }
+
+  @Override
+  public Instant convertToEntityAttribute(Date date)
+  {
+    return date.toInstant();
+  }
+}