2016-09-27 65 views
1

所以我試圖使用Spring Data JPA來使用存儲庫接口來創建一些其他服務。但我堅持要做一些事情,而不必創建自定義控制器。Spring Data JPA和PUT請求創建

假設此服務只接受PUT和GET請求。 PUT請求用於創建和更新資源。所以這個ID就是客戶端生成的。

實體和存儲庫將是這樣的:

@Entity 
public class Document { 
    @Id 
    private String name; 
    private String text; 
     //getters and setters 
} 

@RepositoryRestResource(collectionResourceRel = "documents", path = "documents") 
public interface DocumentRepository extends PagingAndSortingRepository<Document, String> { 
} 

當我嘗試做一個PUT請求@本地:8080 /文件/富與以下機構:

{ 
    "text": "Lorem Ipsum dolor sit amet" 
} 

我得到這個消息:

{ 
    "timestamp": 1474930016665, 
    "status": 500, 
    "error": "Internal Server Error", 
    "exception": "org.springframework.orm.jpa.JpaSystemException", 
    "message": "ids for this class must be manually assigned before calling save(): hello.Document; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): hello.Document", 
    "path": "/documents/foo" 
} 

所以我在給全身:

{ 
    "name": "foo", 
    "text": "Lorem Ipsum dolor sit amet" 
} 

所以它返回創建與

{ 
    "text": "Lorem Ipsum dolor sit amet", 
    "_links": { 
    "self": { 
     "href": "http://localhost:8080/documents/foo" 
    }, 
    "document": { 
     "href": "http://localhost:8080/documents/foo" 
    } 
    } 
} 

201是否有可能使PUT,而無需發送ID(name字段)JSON身體裏面?既然我已經在URI中發送它了?

我知道我可以使用/documents/{document.name}創建一個RestController和一些requestmapping,並在保存之前使用它來設置名稱字段,但我想知道是否有任何註釋或某些東西。

回答

2

你可以只保存之前定義@HandleBeforeCreate/@HandleBeforeSave方法來改變模式:

@Component 
@RepositoryEventHandler(Document.class) 
public class DocumentBeforeSave { 
    @Autowired 
    private HttpServletRequest req; 

    @HandleBeforeCreate 
    public void handleBeforeSave(Document document) { 
     if("PUT".equals(req.getMethod())){ 
      String uri = req.getRequestURI(); 
      uri = uri.substring(uri.lastIndexOf('/') + 1); 
      document.setName(uri); 
     } 
    } 
} 
  • 因爲身體不包含任何ID(在這一點),這兩個POSTPUT將觸發@HandleBeforeCreate方法(如果主體包含idPUT請求寧願觸發@HandleBeforeSave)。
  • 在分配id(爲了讓POST主體不變)之前,我們需要檢查RequestMethod是否爲PUT
  • HttpServletRequest作爲代理注入,可以被多個線程使用。閱讀它:Can't understand `@Autowired HttpServletRequest` of spring-mvc well
+0

非常感謝!我期待着HandleBeforeCreate,但不知道如何注入並獲取URI :) –