gpt4 book ai didi

java - Spring Data REST - 在不创建/搜索/findAll URL 的情况下覆盖存储库 findAll

转载 作者:行者123 更新时间:2023-12-01 22:11:57 25 4
gpt4 key购买 nike

有什么方法可以防止 Spring Data REST 为覆盖的存储库方法创建/search URL?

例如,以下代码会生成一个/search/findAll 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)
...

最佳答案

Is there any way to prevent Spring Data REST from creating a /search URLs for overridden repository methods?

我发现了以下技巧来解决这个问题:

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

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

更多其他这个技巧允许您为“获取所有记录”请求设置默认排序顺序:

@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“所有记录”请求(

关于java - Spring Data REST - 在不创建/搜索/findAll URL 的情况下覆盖存储库 findAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47368898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com