Spring Data REST - 覆盖存储库findAll而不创建/ search / findAll URL

时间:2017-11-18 17:23:44

标签: java spring rest spring-data-rest

有没有办法阻止Spring Data REST为重写的存储库方法创建/搜索URL?

例如,以下代码会生成/ search / findAll URL,该URL会复制集合资源的功能:

public interface EmployeeRepository extends CrudRepository<Employee, Long>
{
    @Override
    @Query("SELECT e FROM Empolyee e")
    Iterable<Employee> findAll();
}

这只是覆盖单个方法时的一个美化问题,但如果您尝试使用相同的函数名和不同的参数覆盖多个方法,例如PagingAndSortingRepository中的两个findAll方法,则spring会抛出异常,因为它正在尝试将2个函数映射到同一个路径。

public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long>
{
    @Override
    @Query("SELECT e FROM Employee e")
    Iterable<Employee> findAll();

    @Override
    @Query("SELECT e FROM Employee e")
    Iterable<Employee> findAll(Sort sort);

    @Override
    @Query("SELECT e FROM Employee e")  
    Page<Employee> findAll(Pageable pageable);
}

结果:

java.lang.IllegalStateException: Ambiguous search mapping detected. Both public abstract java.lang.Iterable uk.co.essl.roster.entity.employee.EmployeeRepository.findAll(org.springframework.data.domain.Sort) and public abstract java.lang.Iterable uk.co.essl.roster.entity.employee.EmployeeRepository.findAll() are mapped to /findAll! Tweak configuration to get to unambiguous paths!
    at org.springframework.data.rest.core.mapping.SearchResourceMappings.<init>(SearchResourceMappings.java:60)
    at org.springframework.data.rest.core.mapping.RepositoryResourceMappings.getSearchResourceMappings(RepositoryResourceMappings.java:128)
    at springfox.documentation.spring.data.rest.EntityContext.searchMappings(EntityContext.java:107)
    ...

2 个答案:

答案 0 :(得分:2)

  

有没有办法阻止Spring Data REST为重写的存储库方法创建/搜索URL?

我找到了以下技巧来解决这个问题:

@Override
default Page<Employee> findAll(Pageable pageable) {
    return findBy(pageable);
}

@RestResource(exported = false)
Page<Employee> findBy(Pageable pageable);

更多其他此技巧允许您设置默认排序顺序以获取所有记录&#39;请求:

@Override
default Page<Employee> findAll(Pageable p) {
    if (p.getSort() == null) {      
        // The default sort order
        return findBy(new PageRequest(p.getPageNumber(), p.getPageSize(), Sort.Direction.DESC, "myField"));
    }
    return findBy(pageable);
}

享受! ))

@RestResource(exported=false)仅用于重写方法无效,导致此阻止 GET &#39;所有记录&#39;请求(

答案 1 :(得分:0)

@RestResource(exported = false)