2016-02-29 61 views
0

我正在寻找如何使用Spring HATEOAS API编程嵌套在HAL中的嵌入_embedded的示例。什么是最佳实践?使用Spring HATEOAS嵌套在HAL中嵌入

这里是我想达到一个例子:

{ 
    "_links": { 
     "self": { "href": "/invoices" } 
    }, 
    "_embedded": { 
     "invoices": [ 
      { 
       "_links": { 
        "self": { "href": "/invoice/1" } 
       }, 
       "_embedded": { 
        "items": [ 
         { "_links": { "self": { "href": "/product/1" }}, "id": 1, "name": "Super cheap Macbook Pro", "price": 2.99 } 
        ] 
       }, 
       "id": 1, 
       "total": 2.99, 
       "no_items": 1 
      }, 
      { 
       "_links": { 
        "self": { "href": "/invoice/2" } 
       }, 
       "_embedded": { 
        "items": [ 
         { "_links": { "self": { "href": "/product/2" }}, "id": 2, "name": "Raspberry Pi", "price": 34.87 }, 
         { "_links": { "self": { "href": "/product/3" }}, "id": 3, "name": "Random product", "price": 30 }, 
         { "_links": { "self": { "href": "/product/4" }}, "id": 4, "name": "More randomness", "price": 30 } 
        ] 
       }, 
       "id": 2, 
       "total": 94.87, 
       "no_items": 3 
      } 
     ] 
    } 
} 
+0

@Dennis。是的,我确实使用两者。 – fellahst

回答

0

使用Spring数据REST和Spring HATEOAS我看到两种方式来实现那种你想要什么轻松。

  1. 创建一个发票和物品实体,并仅为该发票实体创建一个存储库。这将内联项目。缺点是你无法自己查询项目,这可能不是你想要的。
  2. 创建两个实体并为其创建两个存储库。现在在Invoice存储库上创建一个Excerpt,可以查询该存储库并将项目嵌入并包含相应的链接集合。但也有一个缺点:嵌入式项目不会有链接。我认为你应该能够通过在投影中使用资源来在其中包含链接。

使用与项目的订单见一些示例代码:

@Data 
@Entity 
public class Item { 
    @Id 
    @GeneratedValue 
    private Long id; 
    private String name; 
} 

@Data 
@Entity 
@Table(name = "customer_order") 
public class Order { 
    @Id 
    @GeneratedValue 
    private Long id; 
    private String name; 
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) 
    private Collection<Item> items; 
} 

public interface ItemRepository extends CrudRepository<Item, Long> { 
} 

@RepositoryRestResource(excerptProjection = InlineItems.class) 
public interface OrderRepository extends CrudRepository<Order, Long> { 
} 

@Projection(name = "inlineItems", types = Order.class) 
public interface InlineItems { 
    String getName(); 

    Collection<Item> getItems(); 
} 

可以查询这样的订单GET http://localhost:8080/orders/1?projection=inlineItems,这将导致以下结果:

{ 
    "name": "My Order", 
    "items": [ 
    { 
     "name": "Banana" 
    }, 
    { 
     "name": "Apple" 
    } 
    ], 
    "_links": { 
    "self": { 
     "href": "http://localhost:8090/api/orders/1" 
    }, 
    "order": { 
     "href": "http://localhost:8090/api/orders/1{?projection}", 
     "templated": true 
    }, 
    "items": { 
     "href": "http://localhost:8090/api/orders/1/items" 
    } 
    } 
}