I think that java.time.Instant
is the best choice to store a date into DB: it is the most likely TIMESTAMP and you are not depending by timezone, it is just a moment on the time.
JPA supports LocalDate
, LocalTime
, LocalDateTime
etc. but not Instant. Sure, you can use either AttributeConverter
or some libraries like Jadira but why it isn't supported out of the box?
I'll try this again. There is some discussion in the issue. The latest discussion seems to be:
mkarg said: While that is absolutely correct, the technical answer is a bit more complex: What is the final predicate that makes a data type eligible for inclusion in the set of mandatory type mappings?
One could say, that predicate is "being essential" or "being of common use", but who defines what "essential" or "common use" is? See, for some applications, support for java.awt.Image and java.net.URL might be much more essential than support for LocalDate or ZonedDateTime. On the other hand, other applications might be full of LocalDate but never uses Instant. So where exactly to make the cut? This becomes particularly complex when looking at the sheer amount of types found in the JRE, and it is obvious there has to be a cut somewhere. Even JavaFX, which is bundled with the JRE, does not support Instant still in v8, so why should JPA? And looking at the current progress of Project Jigsaw, possibly the qualifying predicate might simply be answered by "all types in a particular jigsaw module"?
Anyways, it is not up to me to decide. I do support your request, and would love to see support for rather all Java Time API times, particularly for Instant and Duration, and your request has prominent supporters like for example Java Champion Arun Gupa as I learned recently. But I doubt the final answer will be as simple an satisfying as we would love to have it.
Maybe it would be better to simply set up another JSR, like "Common Data Type Conversions for the Java Platform", which provides much more mappings than just date and time, but also would not be bound to JPA but also could be used by JAXB, JAX-RS, and possibly more API that deal which the problem of transforming " to "? Having such a vehicle would really reduce boilerplate a lot.
TL-DR; There are a lot of types. We had to draw the line somewhere.
There is a new issue for it to be added to a future JPA version.
Another interesting bit of analysis I found on a thread by Douglas Surber (works on JDBC):
The JDK 8 version of JDBC includes support for most of the SQL types that correspond to 310 classes.
- DATE - LocalDate
- TIME - LocalTime
- TIMESTAMP WITH OUT TIME ZONE - LocalDateTime
- TIMESTAMP WITH TIME ZONE - OffsetDateTime
JDK 8 version of JDBC does not include a mapping between the INTERVAL types and the corresponding 310 classes.
There is no SQL type that exactly corresponds to any other 310 classes. As a result, the JDBC spec is silent for all other classes.
I would strongly encourage JDBC developers to use the new 310 classes. There are problems with java.util.Date, java.sql.Date, java.sql.Time, and java.sql.Timestamp. You should consider them deprecated. The 310 classes are vastly superior.
Douglas
TL:DR; We just picked one Java 8 type for each of the 4 possible ways you might store temporal data in the database.
Finally, if you read through this thread it appears there is significant cultural pressure to keep standard APIs small and simple.
That is a $ 1M question.
Why it wasn't supported in the past, I don't know. It is indeed odd. However, it seems it might become part of upcoming JPA 3.2 Spec. In my opinion Instant
should have been the first JSR-310 type to support - not the last coming along 10 years later.
Here is some background:
Almost all RDBMSes can indeed only store an Instant. Some, like PostgreSQL timestamptz
, will give you the illusion that they can do more, but it is really a hoax as pointed out by many others.
If your entity class looks like this
@Entity
public class MyEntity {
...
@Column(name="created_at")
private ZonedDateTime createdAt;
public ZonedDateTime getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(ZonedDateTime ts) {
this.createdAt = ts;
}
}
you are most likely doing it wrong: With this, your persistence layer code is giving you the illusion that it can store a ZonedDateTime
for you while in reality it can't.
(the notable exception is Oracle Database which can actually store a ZonedDateTime without loss of information, but I must admit I've never seen it used in real life).
I've found this comment:
Instant is not covered by JDBC, so is not by JPA. At least not yet.
which may explain why the JPA maintainers did not (until recently) acknowledge why it should be mentioned in the JPA Spec. But the above statement is wrong. Support for Instant
in JDBC has been there all along. Let me explain:
The JDBC java.sql.Timestamp
and Instant
is essentially the same thing. Except for some edge cases caused by the fact that Instant
can store dates further in the past or into the future than can Date
(which Timestamp
extends from) there is a lossless conversion between the two. (edge cases: we are talking about dates in future year 292,469,238 and beyond which would get you into trouble and similar nonsense on the past side, so yes, for all practical purpose there is lossless conversion between the two).
So all that is left for us is to explain to the JDBC driver that we provide and expect values in UTC.
Suppose we have
private static final Calendar UTC_CAL = Calendar.getInstance(TimeZone.getTimeZone(ZoneOffset.UTC));
then reading an Instant
from a database of column type TIMESTAMP
can be done like this:
Instant myInstant = resultSet.getTimestamp(colIdx, UTC_CAL).toInstant();
while writing can be done like this:
preparedStatement.setTimestamp(colIdx, Timestamp.from(myInstant), UTC_CAL);
It should be noted that the above methodology is "safe", meaning it will work consistently regardless of the database server's setting for default timezone or your own JVM's timezone setting.
As you can imagine, those ORMs which indeed supports Instant
behind the scenes do exactly as above. Hibernate and Nucleus support Instant
, EclipseLink not yet.
Your entity class should simply look like this:
@Entity
public class MyEntity {
...
@Column(name="created_at")
private Instant createdAt;
// getters and setters
}
When using Hibernate, you can find many tales on the Internet of having to set hibernate.jdbc.time_zone
to UTC
. This is not necessary with the above, at least not with Hibernate 6. The reason is that Hibernate can see your intent (you specify Instant
, not any of the other JSR-310 types), so it knows it has to use a static UTC_CAL
when reading or writing the values from/to the database.
Instant
in JPA code ?As stated, Instant
is not currently in the JPA Spec but seems to be finally coming up. There are two reasons why I would gladly use it anyway:
Instant
finally comes to the JPA Spec, I bet it will simply work just like Hibernate already do. So no change.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With