2012-10-23 91 views
2

我正在使用PostgreSQL數據庫& JPA。這裏是我的用戶表比較java中Postgresql中的timestamp日期

CREATE TABLE users 
     (
      id integer NOT NULL DEFAULT nextval('userseq'::regclass), 
      firstname character varying(64) , 
      middlename character varying(64), 
      lastname character varying(64), 
      birthdate timestamp with time zone, 
     ) 

    Query query = em 
        .createQuery(
    "SELECT users FROM Users users WHERE user.birthdate =:a") 
          .setParameter("a",18) 
          .setParameter("b",25); 
      query.getResultList(); 

我想得到所有年齡在18-25之間的用戶。請完成我的上述JPA查詢

+0

您不需要轉換DB的現有'timestamp'。請修改答案。 – CycDemo

回答

2

使用Between運營商,固定到user.birthdateusers.birthdate在第一。

Calendar cal_1 = Calendar.getInstance(); 
    cal_1.add(Calendar.YEAR, -18); 
    Date a = cal_1.getTime(); 
    Calendar cal_2 = Calendar.getInstance(); 
    cal_2.add(Calendar.YEAR, -25); 
    Date b = cal_2.getTime(); 

    query.setParameter("a", a); 
    query.setParameter("b", b); 

    SELECT users FROM Users users WHERE users.eventsDate BETWEEN :a AND :b 

例如:x BETWEEN :min AND :max。參考here

2

JPQL缺乏日期運算符。在SQL你會寫這樣的:

SELECT age(TIMESTAMPTZ '1999-01-01') BETWEEN INTERVAL '18' YEAR AND INTERVAL '25' YEAR; 

但你不能這樣做在JPQL據我所知。 BETWEEN is supported in JPQL,所以我ab轉換日期參數java.util.Date使用java.util.Calendar,然後使用:

SELECT users FROM Users users WHERE user.birthdate BETWEEN :a AND :b