【问题标题】:Spring Data REST and IdClass - not compatible?Spring Data REST 和 IdClass - 不兼容?
【发布时间】:2015-06-25 12:45:45
【问题描述】:

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

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

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

设置: 2 个实体:客户和关系,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));

到目前为止一切顺利。现在让我们通过 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"
}

我总是得到 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"
        }
      }
    } ]
  }
}

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

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

【问题讨论】:

    标签: java spring rest jpa spring-hateoas


    【解决方案1】:

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

    spring data rest with composite primary key

    希望这会对你有所帮助。

    【讨论】:

    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多