【问题标题】:Spring Data REST custom finder for JpaRepositoryJpaRepository 的 Spring Data REST 自定义查找器
【发布时间】:2013-11-23 19:45:47
【问题描述】:

我正在寻找使用通用查找器构建 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 em> 参数(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) 中不可用

我希望有人已经弄清楚了这一点,并愿意给我一些指导。

【问题讨论】:

  • 你有什么收获吗?
  • 并非如此。我已经在 Controller 中进行了大部分自定义 queryDSL 谓词查询,但仍然很高兴知道这是否可行以及如何实现。
  • 我正在尝试解决同样的问题。当您在控制器中实现查询时,您是如何处理分页的?

标签: spring-data-jpa querydsl spring-data-rest


【解决方案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());
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 2015-03-25
    • 2016-01-23
    • 2014-11-16
    • 2018-10-07
    • 2016-02-07
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多