2015-12-20 98 views
3

考慮Custom implementations for Spring Data repositories我使用存儲庫中的@RepositoryRestResource把所有的HATEOAS產生goodnes:春季數據REST/HATEOAS用自定義的方法實現

@RepositoryRestResource(collectionResourceRel = "people", path = "people") 
public interface PersonRepository extends PagingAndSortingRepository<PersonNode,Long>, 
              PersonRepositoryCustom { 


    List<PersonNode> findBySurname(@Param("0") String name); 
} 

現在下面所提到的文檔,我創建了PersonRepositoryCustom額外的,簡單的對於入門的目的方法:

public interface PersonRepositoryCustom { 

    public String printPerson(PersonNode personNode); 
} 

實現是:

public class PersonRepositoryImpl implements PersonRepositoryCustom{ 

    @Override 
    public String printPerson(PersonNode personNode) { 
     return "It Works!"; 
    } 
} 

我想讓默認的SDR自動生成的端點保持不變,只需添加新的自定義方法/新實現。 我該如何使用spring-data Rest/HATEOAS這個自定義方法? 使用簡單的@RepositoryRestResource控制器端點自動生成。如果我想提供一些自定義方法怎麼辦?我認爲我將不得不手動創建控制器,但在這個示例中應該如何看待?

回答

0

添加了自定義方法,以便您可以在您的代碼中使用該方法,在其中您將要使用PersonRepository。它不會神奇地將其映射到REST操作,但現有的PagingAndSortingRepository映射將保留。

0

首先,像public String printPerson(PersonNode personNode)存儲庫這樣的方法是RPC風格的API,它是一個已知的反模式,所以你應該在一個標準的REST的分頻設計的API(例如見How to design REST API for non-CRUD "commands" like activate and deactivate of a resource?

你的問題的解決方案可以如下所示:

  1. 創建自定義@RestController(你應該)與定義@RequestMapping S表示自定義的方法,它調用相關的實現。

  2. 爲您的實體新ResourceProcessor並覆蓋其process方法,添加一個新的鏈接指向像/people/{id}/printPerson或任何你的映射定義是你的自定義方法的資源。

這裏從我的項目的例子(Blog實體需要列出其Categories):

@Component 
public static class BlogResourceProcessor implements ResourceProcessor<Resource<Blog>> { 
    @Override 
    public Resource<Blog> process(Resource<Blog> blogResource) { 
     UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath() 
       .path("/blog/{id}/categories").buildAndExpand(Long.toString(blogResource.getContent().getId())); 
     blogResource.add(new Link(uriComponents.toUriString(), "categories")); 
     return blogResource; 
    } 
}