我希望用通用查找器构建一个REST接口。这个想法是提供一个搜索表单,用户可以通过不提供任何参数来获取所有记录,或者通过键入字段的任意组合来优化搜索结果。
我用@RestResource注释 JpaRepository 的简单示例提供了一种开箱即用的方式来添加查找器@Query
@RestResource(path = "users", rel = "users")
public interface UserRepository extends JpaRepository<User, Long>{
public Page<User> findByFirstNameStartingWithIgnoreCase(@Param("first") String fName, Pageable page);
}
我希望添加一个自定义查找器,该查找器将映射我的参数,并利用分页,排序和REST支持,其中实际的实现查询将动态组合(可能使用QueryDSL),该方法将具有n个参数(p 1 ...p n),看起来像:
public Page<User> findCustom(@Param("p1") String p1, @Param("p2") String p2, ... @Param("pn") String pn, Pageable page);
我尝试了以下方法:
http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations
但我的自定义方法在存储库的 REST 界面(/users/search)中不可用
我希望有人已经想通了这一点,并愿意给我一些方向。
尝试这样的事情,但当然要适应你的场景:
public interface LocationRepository extends CrudRepository,
PagingAndSortingRepository,
LocationRepositoryExt {
}
public interface LocationRepositoryExt {
@Query
public List findByStateCodeAndLocationNumber(@Param("stateCode") StateCode stateCode, @Param("locationNumber") String locationNumber);
}
class LocationRepositoryImpl extends QueryDslRepositorySupport implements LocationRepositoryExt {
private static final QLocation location = QLocation.location;
public LocationRepositoryImpl() {
super(Location.class);
}
@Override
public Page findByStateAndLocationNumber(@Param("state") State state, @Param("locationNumber") String locationNumber, Pageable pageable) {
List locations = from(location)
.where(location.state.eq(state)
.and(location.locationNumber.eq(locationNumber)))
.list(location);
return new PageImpl(locations, pageable, locations.size());
}
}