Pet*_*ler 5 spring spring-data-rest spring-hateoas
在我们的Spring-Data-Rest项目中,我们在/ buergers/search/findBuergerFuzzy?searchString ="..."端点上进行了自定义(模糊)搜索.
是否可以在/ buergers/search端点上添加链接(不覆盖自动公开的Repository findBy方法)?
控制器暴露搜索:
@BasePathAwareController
@RequestMapping("/buergers/search/")
public class BuergerSearchController {
@Autowired
QueryService service;
@RequestMapping(value = "/findBuergerFuzzy", method = RequestMethod.GET)
public
@ResponseBody
ResponseEntity<?> findBuergerFuzzy(PersistentEntityResourceAssembler assembler, @Param("searchString") String searchString) {
if (searchString.length() < 3)
throw new IllegalArgumentException("Search String must be at least 3 chars long.");
List<Buerger> list = service.query(searchString, Buerger.class, new String[]{"vorname", "nachname", "geburtsdatum", "augenfarbe"});
final List<PersistentEntityResource> collect = list.stream().map(assembler::toResource).collect(Collectors.toList());
return new ResponseEntity<Object>(new Resources<>(collect), HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
挖掘spring-data-rest源我找到了RepositorySearchesResource,它似乎解决了这个问题.
@Component
public class SearchResourcesProcessor implements ResourceProcessor<RepositorySearchesResource> {
@Override
public RepositorySearchesResource process(RepositorySearchesResource repositorySearchesResource) {
final String search = repositorySearchesResource.getId().getHref();
final Link findFullTextFuzzy = new Link(search + "/findFullTextFuzzy{?q}").withRel("findFullTextFuzzy");
repositorySearchesResource.add(findFullTextFuzzy);
return repositorySearchesResource;
}
}
Run Code Online (Sandbox Code Playgroud)
因为我们通过模板生成此代码,所以这足以满足我们的需求.确保以正确和安全的方式检查评论.
ResourceSupport 现在是 RepresentationModel
资源现在是 EntityModel
资源现在是 CollectionModel
PagedResources 现在是 PagedModel
新版本代码:
import org.springframework.data.rest.webmvc.RepositorySearchesResource;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.RepresentationModelProcessor;
import org.springframework.stereotype.Component;
@Component
public class RepositorySearchesProcessor implements RepresentationModelProcessor<RepositorySearchesResource> {
@Override
public RepositorySearchesResource process(RepositorySearchesResource model) {
System.out.println(model.getDomainType());
model.add(Link.of(model.getRequiredLink("self").getHref() + "/findFullTextFuzzy{?q}").withRel("findFullTextFuzzy"));
return model;
}
}
Run Code Online (Sandbox Code Playgroud)
关于如何找到你使用的资源或模型,在每个方法中设置断点后RepresentationModel
,你可能会发现一些有用的东西:
归档时间: |
|
查看次数: |
2208 次 |
最近记录: |