简体   繁体   English

JPA:如何比较两个日期

[英]JPA : How to compare two dates

I need to fetch data between two dates in a JPQL query but it doesn't work. 我需要在JPQL查询中的两个日期之间获取数据,但它不起作用。 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 使用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()) 使用datediff将birthdate转换为整数(year,birthdate,getDate())
  • or convert the agefrom into Date using dateadd(year, -agefrom, getDate()), 或者使用dateadd(year,-agefrom,getDate())将agefrom转换为Date,
  • or you can simplify it using datediff(year, birthdate, getDate()) between agefrom and ageto. 或者你可以使用年龄从和年龄之间的datediff(年,生日,getDate())来简化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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