如何使用Spring Data Rest更新具有OneToMany并嵌套ManyToOne关系的REST资源

时间:2015-11-25 13:07:09

标签: spring rest spring-data-jpa spring-data-rest

我有一个简单的发票系统,我需要创建和更新发票。我正在尝试使用Spring Data Rest,但是根据我从文档中获得的内容,我最终会做很多调用来实现更新。

Invoice Model

@Entity
class Article {
    @Id
    @GeneratedValue
    Long ID;
    @Basic
    String name;
}
@Entity
class Invoice {
    @Id
    @GeneratedValue
    Long ID;
    @Basic
    String customer;
    @OneToMany(cascade=CascadeType.ALL)
    List<InvoiceItem> items;

}
@Entity
class InvoiceItem {
    @Id
    @GeneratedValue
    Long ID;
    @Basic
    double amount;
    @ManyToOne
    private Article article;
}

我正在使用Spring Data Rest通过这些Spring Data Rest / JPA存储库将此模型公开给我的web fronend

@RepositoryRestResource(collectionResourceRel = "articles", path = "articles")
interface ArticleJPARepository extends JpaRepository<Article, Long> {}

@RepositoryRestResource(collectionResourceRel = "invoices", path = "invoices")
interface InvoiceJPARepository extends JpaRepository<Invoice, Long> {}

@RepositoryRestResource(collectionResourceRel = "invoiceitems", path = "invoiceitems")
interface InvoiceItemJPARepository extends JpaRepository<InvoiceItem, Long> {}

所以,假设我有一个如下所示的更新表单:

enter image description here

我可以做几件事:

  • 更新发票客户
  • 更改现有InvoiceItem的文章
  • 删除部分InvoiceItems
  • 附加新的InvoiceItem

我从Spring Rest Docs得到的是我现在需要打几个电话。

  1. 我需要PUT /invoices/1
  2. 更新发票客户
  3. 然后在InvoiceItem PUT n PUT /invoiceitems/<x>/
  4. 中更新 n 文章和金额
  5. 追加 m 新的InvoiceItems m POST /invoiceitems然后POST /invoices/1/items
  6. 删除InvoiceItem 2 DELETE /invoiceitems/2,然后删除DELETE /invoices/1/items/<2>
  7. 有没有更简单的方法来实现Spring Data Rest的这种更新?

0 个答案:

没有答案