1
votes

I want to fetch all the records which match the today date but ignoring the year Date in database is like this 1980-11-14. Want to fetch the record only comparing month and day not the year. I tried it using Criteria but its not working. Here is my code.

Date date = new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH, day);

Calendar fromDate = calendar.getInstance();
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH, day);

Calendar toDate = calendar.getInstance();

Criteria criteria=session.createCriteria(Add_Follower.class);
criteria.add(Restrictions.eq("follow_uInfo.id", uid));
criteria.add(Restrictions.between("following_uInfo.dob",fromDate,toDate));
users=criteria.list();
1
Well, Abhi, what happened? Did you get it to work? - Mike Nakis
I am geting exception org.hibernate.QueryException: could not resolve property: Following_uInfo of: com.abhi.model.Add_Follower - Abhijeet Jadhav
@MikeNakis I just want it to know setting the constant year how can it will work I tried it giving the casting exception java.util.GregorianCalendar cannot be cast to java.util.Date. - Abhijeet Jadhav
Regarding could not resolve property, I do not know, that's your code and your properties, you should be able to tell what's wrong, but I see that in one case you say follow_uInfo and in another case you say following_uInfo, could that be a hint? - Mike Nakis
As to how to convert a calendar to date, see stackoverflow.com/q/9112770/773113 - Mike Nakis

1 Answers

1
votes

I did it with a named query and using "EXTRACT",

in this example for birthdays:

SELECT p FROM Person p 
WHERE EXTRACT(DAY FROM p.gebdat) = EXTRACT(DAY FROM NOW())
AND EXTRACT(MONTH FROM p.gebdat) = EXTRACT(MONTH FROM NOW())
ORDER BY p.nachname, p.vorname