4

我有以下问题

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

使用 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> {

}

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

例如,使用 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 代码,但没有保存实体。

有人试过了吗?

4

1 回答 1

1

尝试仅使用 URL。

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"]

因为 Ab 是一个列表,因此您提交了一个数组。不过没有测试这个。

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

于 2014-08-12T18:57:17.850 回答