2

我正在使用 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 查询

4

2 回答 2

2

JPQL 缺少日期运算符。在 SQL 中,您会编写如下内容:

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

但据我所知,你不能在 JPQL 中做到这一点。BETWEEN在 JPQL 中受支持,因此我将日期参数转换为using ,a然后使用:bjava.util.Datejava.util.Calendar

SELECT users FROM Users users WHERE user.birthdate BETWEEN :a AND :b
于 2012-10-23T09:41:38.973 回答
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。参考这里

于 2012-10-23T09:46:59.133 回答