stivlo
stivlo

Reputation: 85506

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 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?

Upvotes: 3

Views: 2388

Answers (1)

Srikanthkumar
Srikanthkumar

Reputation: 69

If anyone looking for the solution

LocalDate instance = LocalDate.now().withYear(year);
LocalDate dateStart = instance.with(firstDayOfYear());
LocalDate dateEnd = instance.with(lastDayOfYear());
eventDao.findAllByEventDateBetween(dateStart, dateEnd);

Upvotes: 1

Related Questions