samedi 4 avril 2015

Find all entities in a year with Spring Data

I am using Spring Data and I have an entity called Event with a field eventDate, which is a java.util.Date.


I would like to find all events in the year, so I first tried to write a method signature:



List<Event> findAllByEventDateYear(String symbol, int year);


But of course it doesn't work, my second attempt was to use Between:



List<Event> findAllByEventDateBetween(Date dateStart, Date dateEnd);


and to make the method more useable, I have added the following to the Service:



private List<Event> findAllByEventDateYear(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_YEAR, 1);
Date dateStart = cal.getTime();

cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31);
Date dateEnd = cal.getTime();

List<Event> quotes = eventDao.findAllByEventDateBetween(dateStart, dateEnd);
return events;
}


Is there a better way to achieve this with Spring Data?


Aucun commentaire:

Enregistrer un commentaire