在java中比较Postgresql中的时间戳日期

时间:2012-10-23 09:38:30

标签: java postgresql jpa

我正在使用PostgreSQL数据库& JPA。这是我的用户表

   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查询

2 个答案:

答案 0 :(得分:2)

日期运算符缺少JPQL。在SQL中你会写一些类似的东西:

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

但据我所知,你不能在JPQL中这样做。 BETWEEN is supported in JPQL,所以我会使用a将日期参数bjava.util.Date转换为java.util.Calendar,然后使用:

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

答案 1 :(得分: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