保存相关实体弹簧数据休息HAL-JSON

时间:2014-03-27 01:17:25

标签: json spring rest hateoas hal-json

我有以下问题

我有弹簧数据休息的基本配置(没有什么花哨,没有自定义)。

使用spring-data-rest-webmvc 2.0.0 RELEASE和spring-data-jpa 1.5.0 RELEASE

A类

@Entity
public class A {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int id

   private String name;

   @ManyToMany
   private List<B> b;

   // getters setters
}

B类

@Entity
public class B {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int id

   private String nameb;

   @ManyToMany(mappedBy = "b")
   private List<A> a;

   // getters setters
}

存储库A

@Repository
@RestResource(rel = "a", path = "a")
public interface ARepository extends PagingAndSortingRepository<A, Integer> {

}

存储库B

@Repository
@RestResource(rel = "b", path = "b")
public interface BRepository extends PagingAndSortingRepository<B, Integer> {

}

当我保存实体工作正常,但我不知道如何保存关系

e.g。使用http

在“B”中保存“A”

这是我在这个答案https://stackoverflow.com/a/13031580/651948

中尝试的最后一件事
POST http://localhost:8080/api/a

{
    "name": "Name of A",
    "b": {
        "rel": "b",
        "href": "http://localhost:8080/api/b/1"
    }
}

我获得了201 http代码,但没有保存实体。

有人试过这个吗?

1 个答案:

答案 0 :(得分:0)

尝试使用网址。

POST http://localhost:8080/api/a
Content-Type: application/json

{
    "name" : "Name of A",
    "b": "http://localhost:8080/api/b/1"
}

或者,在您的情况下,它可能是

"b" :  ["http://localhost:8080/api/b/1"]

因为A.b是一个列表,因此你提交了一个数组。但是没有测试过这个。

这应该是自Spring 2.0以来的有效方式(参见Spring Data Rest 2.0.0.RELEASE Breaks Code Working Previously With RC1),它对我很有用。

相关问题