2012-12-05 60 views
3

我想按日期查找記錄。在實體和數據庫表中,數據類型是時間戳。我使用Oracle數據庫。如何根據JPA標準中timestamp列的日期查找?

@Entity 
public class Request implements Serializable { 
    @Id 
    private String id; 
    @Version 
    private long version; 
    @Temporal(TemporalType.TIMESTAMP) 
    @Column(name = "CREATION_DATE") 
    private Date creationDate; 

    public Request() { 
    } 

    public Request(String id, Date creationDate) { 
    setId(id); 
    setCreationDate(creationDate); 
    } 

    public String getId() { 
    return id; 
    } 

    public void setId(String id) { 
    this.id = id; 
    } 

    public long getVersion() { 
    return version; 
    } 

    public void setVersion(long version) { 
    this.version = version; 
    } 

    public Date getCreationDate() { 
    return creationDate; 
    } 

    public void setCreationDate(Date creationDate) { 
    this.creationDate = creationDate; 
    } 
} 
勉方法

public static void main(String[] args) { 
    RequestTestCase requestTestCase = new RequestTestCase(); 
    EntityManager em = Persistence.createEntityManagerFactory("Criteria").createEntityManager(); 

    em.getTransaction().begin(); 
    em.persist(new Request("005",new Date())); 
    em.getTransaction().commit(); 

    Query q = em.createQuery("SELECT r FROM Request r WHERE r.creationDate = :creationDate",Request.class); 
    q.setParameter("creationDate",new GregorianCalendar(2012,12,5).getTime()); 
    Request r = (Request)q.getSingleResult(); 
    System.out.println(r.getCreationDate());   

} 

在Oracle數據庫中的記錄是,

ID  CREATION_DATE     VERSION 

006  05-DEC-12 05.34.39.200000 PM 1 

的例外是,

Exception in thread "main" javax.persistence.NoResultException: getSingleResult() did  not retrieve any entities. 
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.throwNoResultException(EJBQueryImpl.java:1246) 
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:750) 
at com.ktrsn.RequestTestCase.main(RequestTestCase.java:29) 
+0

你能否更新相關代碼及其問題 –

回答

2

的DB型是TIMESTAMP而不是DATE,我你存儲確切的時間。

當使用new GregorianCalendar(2012,12,5).getTime()你quering 00匹配給定的日期時間標記:00:00.000,並且不會在你的數據庫中存在

您應該更改數據庫,而不是存儲時間戳的日期或更改查詢。

JPA 2得到了年,月,日功能,這樣你就可以

SELECT WHERE YEAR(yourdate) = YEAR(dbdate) AND MONTH(yourdate) = MONTH(dbdate) and DAY(yourdate) = DATE(dbdate)

在標準API,你可以做這樣的事情:

Expression<Integer> yourdateYear = cb.function("year", Integer.class, yourdate); 
Expression<Integer> yourdateMonth = cb.function("month", Integer.class, yourdate); 
Expression<Integer> yourdateDay = cb.function("day", Integer.class, yourdate); 

然後用與表達,並結合他們對db中的日期字段做相同的操作並進行比較。

+0

'code'SELECT WHERE YEAR(yourdate)= YEAR(dbdate )AND MONTH(yourdate)= MONTH(dbdate)和DAY(yourdate)= DATE(dbdate)'code'如何使用JPA 2.0 Criteria API編寫 –

0

您可以在jpql中使用本機查詢。

實施例(SQL服務器):

select table from table where convert(date,mydate)=:date_colum 
0

最簡單的方法來比較兩個日期時間

比較兩個日期和忽略時間的日期

WHERE DATE(dbdDate)= DATE(你的日期)