Mapping DATE and TIME in JPA (Hibernate) entity

Mapping DATE and TIME from database to java.util.Date using @Temporal annotation in JPA (Hibernate) entity. Information about using Timestamp. Presented on web application and MySQL database.

Different database systems handle date and time in a different way. For example MySQL database has types DATE, DATETIME and TIMESTAMP. Oracle database has type DATE, which includes date and time and next it has type TIMESTAMP. On the other hand in Java you usually use instance of java.util.Date or java.sql.Timestamp.

With Timestamp it's very easy. If you have in your database column with type TIMESTAMP, create in your entity an attribute with type java.sql.Timestamp and you have successfully mapped this column.

But if you have in your database something else, like DATE, TIME or DATETIME, you can map this type to java.util.Date. It can be even something else like java.sql.Date or java.util.Calendar, but most people use java.util.Date.

But java.util.Date contains both date and time! So you must somehow specify what is really in your database, be it DATE, TIME or both.

I added to my sample database to table CUSTOMERS a column REGISTRATION_DATE, which is of type DATE. Now I want to show value of this column in my sample web application. Currently I show just name and image of each customer. I also want to show value of column REGISTRATION_DATE.

First I must add to my entity an attribute registrationDate, which is of type java.util.Date. To map it to database, I must use annotation @Temporal. Inside this annotation I must specify what is really in my database: DATE, TIME or both - TIMESTAMP. Now I will simply print the value of this attribute in a JSP file.

comments powered by Disqus


Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects: