简体   繁体   中英

Giving criteria in hibernate query to get values having start date as previous month's date i.e current month minus 1

Giving criteria in hibernate query to get values having start date as previous month's date ie current month minus 1.

I have a table in database that has a date field. I want to write a hibernate query in which i will get values from that table whose date falls under the range :- current date to 30 days minus the current date.

Here's the query.. select whatever whatever from PaymentInSlipDO pis, InwardDO inw, InwardPaySlipMapDO map where map.inwardSeq = inw.id
and map.parentGuidObj = pis.id and pis.paySlipStatus<>'CANCELLED' and pis.paySlipDt<= (THIS IS WHER I AM STUCK)

Clearly, subtracting 30 days is not the correct way to do this, as you might end up with the same month (if you were on the 31st of the current month) or end up going back two months (if the date was March 1st, because February only has 28 days).

The best solution is to use the DATEADD or ADDDATE function because it can use specific date units like minutes, hours, days, months, years and so on. Just use minus instead of plus to go backwards. Most databases have a DATEADD function but their parameters may vary, so check your documentation.

Another option is to use the DATEPART function to get the month portion and parse it as an integer before comparing it as needed. Again, don't just subtract one month, otherwise you'll have problems next January!

Try using Calendar:

final String queryStr = 
      "select whatever whatever " +
      "from PaymentInSlipDO pis, InwardDO inw, InwardPaySlipMapDO map " +
      "where map.inwardSeq = inw.id " +
      "and map.parentGuidObj = pis.id and pis.paySlipStatus<>'CANCELLED' " +
      "and pis.paySlipDt<= :date";

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, -1);

query.setParameter("date", c.getTime());

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