如何在JPA标准从时间戳列日找?(How to find by date from timestam

2019-07-04 13:41发布

我想找到日的记录。 在实体和数据库表,数据类型是时间戳。 我使用Oracle数据库。

@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)

Answer 1:

该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);

然后,与和表达它们结合在一起,做同样的分贝日期字段并加以比较。



Answer 2:

最简单的方法来比较两个日期时间的日期

比较两个日期和时间忽略

WHERE DATE(dbdDate)= DATE(yourDate)



Answer 3:

您可以在JPQL使用本机查询。

实施例(SQL服务器):

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


文章来源: How to find by date from timestamp column in JPA criteria?