问题
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.
回答1:
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 in Repsitory.
For example you can declare:
public interface SharedRepository<T, ID> extends CrudRepository<T, ID> {
List<T> findByStartDateAndEndDate(LocalDate startDate, LocalDate endDate);
}
Then extend from this new interface for your entities
@Repository
public interface PersonRepisotry extends SharedRepository<Person, Long> {
}
@Repository
public interface RoomRepository extends SharedRepository<Room, Long> {
}
Both PersonRepository
and RoomRepository
will have findByStartDateAndEndDate
method.
回答2:
Spring now supports a kind of query by example
Service:
Person person = new Person();
person.setFirstname("Dave");
Example<Person> example = Example.of(person);
Repo Interface:
public interface QueryByExampleExecutor<T> {
<S extends T> S findOne(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example);
}
来源:https://stackoverflow.com/questions/54834170/how-to-make-a-generic-repository-in-spring-boot-that-accepts-an-entity-and-few-a