【发布时间】:2016-03-06 01:19:24
【问题描述】:
我想将自定义搜索端点添加到我现有的用户存储库。
我的用户存储库如下所示:
@RepositoryRestResource(collectionResourceRel="users", path="users")
public interface UserRepository extends PagingAndSortingRepository<User, Long>{
User findByUsername(String username);
}
自定义控制器:
@BasePathAwareController
@RequestMapping("users/search")
public class CustomController implements ResourceProcessor<RepositorySearchesResource>, ResourceAssembler<User, Resource<User>> {
@Autowired
UserRepository userReposiotry;
@Autowired
private EntityLinks entityLinks;
@RequestMapping(value = "findFirst", produces = "application/json")
@ResponseBody
public ResponseEntity<Resource<User>> findFirstUser() {
Resource<User> resource = toResource(userReposiotry.findOne(1L));
return new ResponseEntity<Resource<User>>(resource, HttpStatus.OK);
}
@Override
public RepositorySearchesResource process(RepositorySearchesResource resource) {
LinkBuilder lb = entityLinks.linkFor(User.class, "username");
resource.add(new Link(lb.toString() + "/search/findFirst", "findFirst"));
return resource;
}
@Override
public Resource<User> toResource(User user) {
Resource<User> resource = new Resource<User>(user);
return resource;
}
}
这将为用户返回正确的搜索端点:
{
"_links": {
"findByUsername": {
"href": "http://localhost:8080/api/users/search/findByUsername"
},
"self": {
"href": "http://localhost:8080/api/users/search"
},
"findFirst": {
"href": "http://localhost:8080/api/users/search/findFirst",
"templated": true
}
}
}
但也适用于邀请等其他端点:
{
"_links": {
"findUserByInvite": {
"href": "http://localhost:8080/api/invites/search/findUserByInvite"
},
"self": {
"href": "http://localhost:8080/api/invites/search"
},
"findFirst": {
"href": "http://localhost:8080/api/invites/search/findFirst",
"templated": true
}
}
}
这怎么能仅限于用户? 谢谢
【问题讨论】:
标签: java spring spring-data spring-data-rest