简体   繁体   中英

JPA : How to compare two dates

I need to fetch data between two dates in a JPQL query but it doesn't work. The dates are in integer but i want to compare with Dates. Here is partial query,

Thanks!

     Query query = em.createQuery
    ("select p1 from Profile p1, Preference p2 where 
(p1.birthdate >= p2.agefrom and p1.birthdate <= p2.ageto and p2.preferenceid=:a)")
                                        .setParameter("a", profileid);


                TABLE Profile {
                profileid integer,
                birthdate date
                }

                TABLE Preference {
                preferenceid integer,
                agefrom integer,
                ageto integer
                }

Use BETWEEN

Query query = em.createQuery("select p1 from Profile p1, Preference p2 where 
   p1.birthdate BETWEEN p2.agefrom AND p2.ageto and p2.preferenceid=:a)")

I don't think you can compare Date and Integer. You have to either :

  • convert the birthdate into integer using datediff(year, birthdate, getDate())
  • or convert the agefrom into Date using dateadd(year, -agefrom, getDate()),
  • or you can simplify it using datediff(year, birthdate, getDate()) between agefrom and ageto.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM