gpt4 book ai didi

java - Spring Data Rest 将自定义端点添加到特定存储库

转载 作者:搜寻专家 更新时间:2023-11-01 03:19:49 24 4
gpt4 key购买 nike

我想将自定义搜索端点添加到我现有的用户存储库。

我的用户存储库如下所示:

@RepositoryRestResource(collectionResourceRel="users", path="users")
public interface UserRepository extends PagingAndSortingRepository<User, Long>{

User findByUsername(String username);
}

自定义 Controller :

@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
}
}
}

这怎么能仅限于用户?谢谢

最佳答案

我假设您的邀请端点也返回一个 RepositorySearchesResource ?!每当 spring-data-rest 序列化一个 RepositorySearchesResource 时,你的 ResourceProcessor 就会被调用。如果您想要为用户和邀请提供不同的链接,您有一些选择:

  • 为您的搜索端点使用不同的返回类型,以便您可以有不同的 ResourceProcessor 实现
  • 在您的 ResourceProcessor 中添加更多逻辑,以区分您是在邀请还是用户用例中

关于java - Spring Data Rest 将自定义端点添加到特定存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031913/

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