我想按日期查找记录。在实体和数据库表中,数据类型是时间戳。我使用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)