Spring Data REST自定义JpaRepository查找器

5
我希望构建一个具有通用查找器的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)中使用。希望有人已经解决了这个问题并能给我一些指导。

你在这方面有什么进展了吗? - wenic
并不是。我已经在控制器中使用大部分自定义的queryDSL谓词查询,但如果知道是否可能以及如何实现仍然是很好的。 - nyl66
我正在尝试解决同样的问题。当你在控制器中实现查询时,你是如何处理分页的? - JBCP
1个回答

1

尝试像这样做,但当然要根据您的情况进行调整:

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());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接