Spring Data JPA - How can I fetch data from a Date column using only month and day?

Matias Diez :

I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

1935-12-08 00:00:00

If I want to do this in a db level it works fine:

SELECT * FROM my_database.event where event_date LIKE '%-12-08%';

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

Matias Diez :

Use nativeQuery to emulate the query in the Database.

@Query(value = "SELECT * FROM events WHERE event_date Like %?1%", nativeQuery = true)
List<Match> findByMatchMonthAndMatchDay(@Param ("eventDate") String eventDate);

The DB takes care of the conversion between Date/String for the LIKE clause.

Passing the param as "-month-day" (e.g.: -12-08) will return a collection of events with that string in the date field.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466346&siteId=1