如何在Spring Boot中制作一个通用存储库,该存储库接受实体,几乎没有属性并根据属性返回所有记录



我想制作一个通用存储库,该存储库接受实体类,少数属性start_date和end_date等属性等,并返回表中的所有记录。

要使用存储库来获取单个实体的结果,我需要编写自定义查询。我不确定如何以通用方式为任何通过属性传递和过滤的实体编写自定义查询。

由于您使用的是弹簧数据JPA,您可以使用自己的方法声明自己的共享存储库接口,并避免自定义查询。CrudRepository使用相同的方法来提供Repsitory中不存在的其他方法。

例如,您可以声明:

public interface SharedRepository<T, ID> extends CrudRepository<T, ID> {
  List<T> findByStartDateAndEndDate(LocalDate startDate, LocalDate endDate); 
}

然后从这个新界面延伸到您的实体

@Repository
public interface PersonRepisotry extends SharedRepository<Person, Long> {
}
@Repository
public interface RoomRepository extends SharedRepository<Room, Long> {
}

PersonRepositoryRoomRepository都将具有findByStartDateAndEndDate方法。

spring现在通过示例支持一种查询

服务:

Person person = new Person();
person.setFirstname("Dave");
Example<Person> example = Example.of(person); 

repo接口:

public interface QueryByExampleExecutor<T> {
   <S extends T> S findOne(Example<S> example);
   <S extends T> Iterable<S> findAll(Example<S> example);
}

最新更新