Spring Data REST 和 IdClass - 不兼容?

Oli*_*ien 6 java rest spring jpa spring-hateoas

我正在尝试将 Spring Data REST 与给定的 SQL 模式一起使用,该模式将 JPA @IdClass 注释用于关联表(交集表或多对多解析表)。这些映射实体未正确序列化。

我创建了一个小项目,它说明了这个问题。它是 spring-data-examples 的一个分支,非常简单。它正在使用 eclipselink,但我已经用 Hibernate 对其进行了测试,问题是一样的。

https://github.com/otrosien/spring-data-examples/tree/idClassFailureWithSerializable

设置:2个实体:Customer和Relationship,2个存储库:CustomerRepository、RelationshipRepository,都扩展了CrudRepository

客户有一个生成的 Id 和名字,姓氏作为字符串。关系具有 IdClass "RelationshipID" 和 customer1、customer2 作为复合主键,两者在 Customer 上都有外键。加上一个关系字符串。

基本集成测试显示实体按预期工作。

Customer dave = customers.save(new Customer("Dave", "Matthews"));
Customer jack = customers.save(new Customer("Jack", "Johnson"));

assertThat(customers.findOne(dave.getId()), is(dave));
assertThat(customers.findOne(jack.getId()), is(jack));

Relationship rel = relationships.save(new Relationship(dave, jack, "likes"));
assertThat(relationships.findOne(rel.pk()), is(rel));
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。现在让我们通过 REST API 试试这个。

POST http://localhost:8080/customers
Content-Type: application/json

{
  "lastname" :"Dave",
  "firstname":"Matthews"
}

POST http://localhost:8080/customers
Content-Type: application/json

{
  "lastname" :"Jack",
  "firstname":"Johnson"
}

POST http://localhost:8080/relationships
Content-Type: application/json

{
  "customer1" : "http://localhost:8080/customers/1",
  "customer2" : "http://localhost:8080/customers/2",
  "relation" : "likes"
}
Run Code Online (Sandbox Code Playgroud)

我总是得到 201 Created,这很好。但是映射实体的表示看起来很糟糕。它们似乎是序列化对象,而不是正确的链接。

GET /relationships

200 OK
{
  "_embedded" : {
    "relationships" : [ {
      "relation" : "likes",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/relationships/Customer%20%5Bid=2,%20firstname=F,%20lastname=L%5D"
        },
        "customer1" : {
          "href" : "http://localhost:8080/relationships/Customer%20%5Bid=2,%20firstname=F,%20lastname=L%5D/customer1"
        },
        "customer2" : {
          "href" : "http://localhost:8080/relationships/Customer%20%5Bid=2,%20firstname=F,%20lastname=L%5D/customer2"
        }
      }
    } ]
  }
}
Run Code Online (Sandbox Code Playgroud)

问题:有没有人成功地将 Spring Data REST 与映射实体一起使用?你能发现实施中的错误吗?或者这是一个错误?(我使用的是带有 starter-data-rest 和 starter-data-jpa 的 spring boot 1.2.4.RELEASE,它们应该都是最新版本)

请不要建议更改架构。我已经知道我可以通过将生成的 @Id 插入到关系中来修复它,但模式是按原样给出的。

kid*_*uit 0

我通过自定义 BackendIdConverter 解决了该问题。

Spring数据使用复合主键

希望对你有帮助。