I want to make a generic repository that accepts the entity class and few attributes like start_date and end_date, etc and returns all the records in the table.
To fetch the results for a single entity using repository I will need to write a custom query. I am not sure how would I write a Custom query in a generic way for any entity that is passed and filter according to the attributes.
Since you are using Spring Data JPA you can declare your own shared repository interface with your own methods and avoid a custom query. The same approach is used by
CrudRepository
to provide additional methods which are not present inRepsitory
.For example you can declare:
Then extend from this new interface for your entities
Both
PersonRepository
andRoomRepository
will havefindByStartDateAndEndDate
method.Spring now supports a kind of query by example
Service:
Repo Interface: