The format goes like this:
@Temporal(TemporalType.DATE)
@Column(name="CREATED_DATE")
private Date createdDate;
My question is: Why is it necessary to annotate mapped java.util.Date fields as @Temporal in javax.persistence? If the local variable is obviously declared as a Date and the column data type in the DB is also one of the date(time) or timestamp types, shouldn't it be easy to infer that we're dealing with a temporal bit of data without redundantly specifying it in multiple places?
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
来源:https://stackoverflow.com/questions/27430318/why-is-it-necessary-to-annotate-mapped-date-fields-temporal-in-javax-persistenc