2017-08-11 156 views
1

我創建了需要實體轉化爲資源定製控制器實體轉化爲資源,定製控制器。我使用@RepositoryRestResource註釋來註釋我的存儲庫。我想知道是否有辦法,我可以從中序列化實體資源的鏈接嵌入其中的其他實體我自定義控制器調用春天數據REST的默認功能。春天DATA REST - 如何使用默認的春天實現

我不想從我的處理方法,但資源返回實體。

謝謝。

+1

不要忘了接受/給予好評的答案,如果它幫助你..) – Cepr0

回答

1

非常簡單,使用對象ResourceResources。例如 - 在此控制器,我們添加自定義的方法,該方法返回所有用戶角色這是枚舉列表:

@RepositoryRestController 
@RequestMapping("https://stackoverflow.com/users/roles") 
public class RoleController { 

    @GetMapping 
    public ResponseEntity<?> getAllRoles() { 
     List<Resource<User.Role>> content = new ArrayList<>(); 
     content.addAll(Arrays.asList(
       new Resource<>(User.Role.ROLE1), 
       new Resource<>(User.Role.ROLE2))); 
     return ResponseEntity.ok(new Resources<>(content)); 
    } 
} 

要添加鏈接的資源,你必須使用對象RepositoryEntityLinks,例如:

@RequiredArgsConstructor 
@RepositoryRestController 
@RequestMapping("/products") 
public class ProductController { 

    @NonNull private final ProductRepo repo; 
    @NonNull private final RepositoryEntityLinks links; 

    @GetMapping("/{id}/dto") 
    public ResponseEntity<?> getDto(@PathVariable("id") Integer productId) { 
     ProductProjection dto = repo.getDto(productId); 

     return ResponseEntity.ok(toResource(dto)); 
    } 

    private ResourceSupport toResource(ProductProjection projection) { 
     ProductDto dto = new ProductDto(projection.getProduct(), projection.getName()); 

     Link productLink = links.linkForSingleResource(projection.getProduct()).withRel("product"); 
     Link selfLink = links.linkForSingleResource(projection.getProduct()).slash("/dto").withSelfRel(); 

     return new Resource<>(dto, productLink, selfLink); 
    } 
} 

有關更多示例,請參閱我的'how-to'和sample project