2016-09-27 23 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要求する@ localhostのようにしよう:8080 /文書/ fooの以下のボディを持つ:

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

Iをこのメッセージが表示されます。

{ 
    "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" 
} 

ので、それは201が

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

で作成し返すことは、JSON本体の内部ID(名前フィールド)を送信することなく、PUTを作ることは可能ですか?私はすでにURIでそれを送信しているので?

RestControllerを作成して/documents/{document.name}でrequestmappingを作成し、保存する前に名前フィールドを設定することができますが、注釈などがあるかどうかを知りたかった。

答えて

2

あなたはそれを保存する前にモデルを変更する@HandleBeforeCreate/@HandleBeforeSave方法を定義できます体が(この時点では)任意のIDが含まれていないので、POSTPUTの両方がトリガされます

@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); 
     } 
    } 
} 
  • @HandleBeforeCreateメソッド(本体にidが含まれている場合、PUTリクエストは@HandleBeforeSaveをトリガーします)。
  • idを割り当てる前にRequestMethodPUTであるかどうかを確認する必要があります(POSTのボディを変更しないでください)。
  • HttpServletRequestはプロキシとして注入され、複数のスレッドで使用できます。読む:Can't understand `@Autowired HttpServletRequest` of spring-mvc well
+0

ありがとう!私はHandleBeforeCreateの周りに何かを期待していたが、注入してURIを取得する方法を知らなかった:) –

関連する問題