Why is it necessary to annotate mapped Date fields @Temporal in javax.persistence?

爱⌒轻易说出口 提交于 2019-12-05 18:02:17

From e.g. java.util.Date it's not obvious if one wants to map to DATE or TIMESTAMP database type. Only exception is java.sql.Date/Time.

When you want to store a java.util.Date in database, it can be done in three different ways:

1- store just the date (java.sql.Date): year/month/day

2- store date and time (java.sql.Time): Date + hour/minute/second

3- store timestamp (java.sql.Timestamp): Date + Time + nano seconds

With providing @Temporal You have to select TemporalType.DATE, TemporalType.TIME, or TemporalType.TIMESTAMP to determine the accuracy of your java.util.Date

From the wikipedia page, this answered it for me:

"If you map a Java java.sql.Date type to a database DATE, this is just a basic mapping and you should not have any issues (ignore Oracle's DATE type that is/was a timestamp for now). You can also map java.sql.Time to TIME, and java.sql.Timestamp to TIMESTAMP. However if you have a java.util.Date or java.util.Calendar in Java and wish to map it to a DATE or TIME, you may need to indicate that the JPA provider perform some sort of conversion for this. In JPA the @Temporal annotation or element is used to map this. You can indicate that just the DATE or TIME portion of the date/time value be stored to the database. You could also use Temporal to map a java.sql.Date to a TIMESTAMP field, or any other such conversion."

So in short, you need @Temporal as a conversion layer between your java type and the target database

If you want to create your database tables from your jpa annotated code (On server startup, etc) then the @Temporal annotation is necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!