spring-data-jpa 如何在Spring Data REST中公开所有存储库的自定义方法?

wqlqzqxt  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(141)

我需要向我的所有Spring Data REST存储库添加一个查询端点。

/api/users/query?query=...
/api/issues/query?query=...
/api/projects/query?query=...
...

/api/users/search/query?query=...
/api/issues/search/query?query=...
/api/projects/search/query?query=...
...

URL格式无关紧要。
我实现了一个自定义的基本存储库:
第一个
请确保Spring Data REST不会公开findAllByQuery方法:

我可以为每个实体类型实现一个控制器,并公开这样一个方法:

@RepositoryRestController
public class UserController {
    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping(path = "/users/search/query")
    public ResponseEntity<CollectionModel<PersistentEntityResource>> findAllByQuery(
            String query,
            Pageable pageable,
            PagedResourcesAssembler<Object> pagedAssembler,
            PersistentEntityResourceAssembler resourceAssembler) {
        return ResponseEntity.ok(pagedAssembler.toModel(
                userRepository.findAllByQuery(value, pageable).map(Object.class::cast),
                resourceAssembler));
    }
}

但是,是否有可能将此方法一次性添加到所有实体中,而无需创建多个相同的控制器?

voj3qocg

voj3qocg1#

以下是我的工作:

@RepositoryRestController
public class QueryController {

    private final ApplicationContext context;

    public QueryController(ApplicationContext context) {
        this.context = context;
    }

    @GetMapping(value = "/{repository}/query")
    public ResponseEntity<Object> findAllByQuery(
            RootResourceInformation resourceInformation,
            String query, Pageable pageable,
            PagedResourcesAssembler<Object> pagedAssembler,
            PersistentEntityResourceAssembler resourceAssembler) {
        Repositories repositories = new Repositories(context);
        Optional<QueryableRepository<?, ?>> repository = repositories
                .getRepositoryFor(resourceInformation.getDomainType())
                .filter(QueryableRepository.class::isInstance)
                .map(QueryableRepository.class::cast);
        if (repository.isPresent()) {
            return ResponseEntity.ok(pagedAssembler.toModel(
                    repository.get()
                            .findAllByQuery(query, pageable)
                            .map(Object.class::cast),
                    resourceAssembler));
        } else {
            return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build();
        }
    }
}

相关问题