How to make a generic repository in Spring Boot that accepts an entity and few attributes and returns all the records based on the attributes?

橙三吉。 提交于 2019-12-11 10:05:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!