How to use date in persistence

In today's post I would like to describe how to use date data type in persistence class and then in queries. We very often use java.util.Date or java.util.Calendar objects in Java, these types can be used in persistence as well. In persistence class you can use Temporal annotation for specifying how the date property should be persisted. Without using Temporal annotation the property is persisted as TIMESTAMP. The TemporalType defines the mapping for temporal type, i.e. DATE, TIME, TIMESTAMP. The example is below:
     @Temporal(TemporalType.TIME)
     public Date getDueTime(){
       return dueDate;
     }
  
In this example dueDate will be persisted as java.sql.Date. Now, this property will be used in query. We should use setParameter in Entitymanager class and specify TemporalType for query like:
   List currentPlans = em.createQuery("SELECT a FROM Plan a WHERE a.creationTime  <= :time").
         setParameter("time", new Date(), TemporalType.TIME).getResultList();
   
Comments:

Post a Comment:
Comments are closed for this entry.
About

pblaha

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today
Bookmarks