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

梦想与她 提交于 2019-12-22 08:47:22

问题


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?


回答1:


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.




回答2:


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




回答3:


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




回答4:


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

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