2

I am using PostgreSQL database & JPA. Here is my user table

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

I want get all user whose age in between 18-25. Please complete my above JPA query

1
  • you don't need to convert existing timestamp of DB. revised the answer, please. Commented Oct 23, 2012 at 10:08

2 Answers 2

2

Use Between operator, fix to user.birthdate to users.birthdate at first.

    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

Example : x BETWEEN :min AND :max. Reference here

Sign up to request clarification or add additional context in comments.

Comments

2

JPQL is lacking in date operators. In SQL you'd write something like:

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

but you can't do that in JPQL as far as I can tell. BETWEEN is supported in JPQL, so I'd convert the date parameters a and b to java.util.Date using java.util.Calendar, then use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.