2017-10-05 216 views
1

我有一個Spring Boot 1.5.7,Spring Data REST,Hibernate,Spring JPA,Swagger2的項目。使用Spring Data REST自定義端點

我有兩個bean這樣的:

@Entity 
public class TicketBundle extends AbstractEntity { 
    private static final long serialVersionUID = 404514926837058071L; 

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) 
    private List<Note> notes = new ArrayList<>(); 

    ..... 
    } 

@Entity 
public class Note extends AbstractEntity { 
    private static final long serialVersionUID = -5062313842902549565L; 

    @Lob 
    private String text; 
    ... 
    } 

我通過庫暴露我的方法:

@Transactional 
@RepositoryRestResource(excerptProjection = TicketBundleProjection.class) 
@PreAuthorize("isAuthenticated()") 
public interface TicketBundleRepository extends PagingAndSortingRepository<TicketBundle, Long> { 
.... 
} 

所以招搖我看到了終點其中我感興趣的是需要從特定的票據集中加載票據集合:

enter image description here

現在,我想重寫默認GET /api/v1/ticketBundles/{id}/notes和替換我的自定義方法,我把TicketBundleRepository

@Transactional(readOnly = true) 
@RestResource(rel = "ticketBundleNotes", path = "/ticketBundles/{id}/notes") 
@RequestMapping(method = RequestMethod.GET, path = "/ticketBundles/{id}/notes") 
@Query("SELECT n FROM TicketBundle tb JOIN tb.notes n WHERE tb.id=:id ORDER BY n.createdDate DESC,n.id DESC") 
public Page<Note> getNotes(@Param("id") long id, Pageable pageable); 

這是非常方便的建立這樣的查詢,因爲我需要使用Pageable並返回一個頁面。不幸的是,我現在有兩個問題。

首先問題 的方法被映射到的/api/v1/ticketBundles/ticketBundles/{id}/notes enter image description here

問題二端點/api/v1/ticketBundles/search/ticketBundles/{id}/notes instad 當我調用該方法從招搖我收到HTTP 404:

請求看起來不對。似乎路徑變量不被理解:

curl -X GET --header 'Accept: application/json' 'http://localhost:8080/api/v1/ticketBundles/search/ticketBundles/{id}/notes?id=1' 

這是來自服務器的響應:

{ 
    "timestamp": "2017-10-05T14:00:35.563+0000", 
    "status": 404, 
    "error": "Not Found", 
    "message": "No message available", 
    "path": "/api/v1/ticketBundles/search/ticketBundles/%7Bid%7D/notes" 
} 

而不在服務器側上的任何錯誤。

有沒有辦法覆蓋端點GET/api/v1/ticketBundles/{id}/notes通過Repository暴露它沒有使用自定義控制器(使用,我會失去設施來管理Pageable)?

此外,我做錯了在上面顯示的電話中獲取HTTP 404?

回答

0

我相信你使用的是不正確的註釋。您需要用@RestController註釋您的課程,並在您的方法上使用@PathVariable而不是@Param。這是一個工作示例,您可能需要根據自己的需求對其進行調整。

@org.springframework.data.rest.webmvc.RepositoryRestController 
@org.springframework.web.bind.annotation.RestController 
public interface PersonRepository extends org.springframework.data.repository.PagingAndSortingRepository<Person, Long> { 

    @org.springframework.web.bind.annotation.GetMapping(path = "/people/{id}") 
    Person findById(@org.springframework.web.bind.annotation.PathVariable("id") Long id); 

} 
+0

感謝您的回覆。不幸的是,根據這個https://jira.spring.io/browse/DATAREST-1154,不可能將@PathVariable用於RestRepository。我試過你的例子,並不適合我。我正在使用Spring Data REST。謝謝! – drenda

相關問題