3

日付でレコードを探したい。エンティティおよびデータベーステーブルでは、データ型はタイムスタンプです。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)
4

3 に答える 3

4

DB タイプはTIMESTAMPでありDATE、正確な時間を保存することを意味します。

使用new GregorianCalendar(2012,12,5).getTime()する場合、00:00:00.000 で指定された日付に一致し、DB に存在しないタイムスタンプを照会しています。

タイムスタンプではなく日付を格納するように DB を変更するか、クエリを変更する必要があります。

JPA 2 には、YEAR、MONTH、および DAY 関数があるため、次のことができます。

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

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

次に、それらを AND 式で結合し、db の日付フィールドに対して同じことを行い、それらを比較します。

于 2012-12-05T11:16:17.640 に答える
0

jpql でネイティブ クエリを使用できます。

例 (SQL サーバー):

select table from table where convert(date,mydate)=:date_colum
于 2015-11-10T02:18:13.940 に答える