当前位置: 代码迷 >> java >> 父 id 未保存在子表 Spring JPA2 @OneToMany 关系中
  详细解决方案

父 id 未保存在子表 Spring JPA2 @OneToMany 关系中

热度:60   发布时间:2023-07-31 13:45:28.0

我有如下所示的 json,它来自我通过 open feign 客户端获取的第三方服务。 我正在尝试使用 Spring JPA2 将这些详细信息保存到我的 MySQL 数据库中。

[
  {
    "request_id": 111,
    "name": "ABC",
    "groups": [
      {
        "id": 21,
        "group": "grp_A"
      },
      {
        "id": 22,
        "group": "grp_B"
      }
    ]
  },
  {
    "request_id": 222,
    "name": "ABC",
    "groups": [
      {
        "id": 23,
        "group": "grp_C"
      }
    ]
  },
  {
    "request_id": 333,
    "name": "ABC",
    "groups": [
      {
        "id": 24,
        "group": "grp_A"
      }
    ]
  },
  {
    "request_id": 444,
    "name": "ABC",
    "groups": [
      {
        "id": 25,
        "group": "grp_C"
      }
    ]
  },
  {
    "request_id": 555,
    "name": "ABC",
    "groups": []
  }
]

我已经为上面的 json 编写了映射,如图所示

请求.java

@Entity
@Table(name = "requests")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Requests {

    @Id
    @Column(name = "request_id")
    private String id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "id", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Groups> groups = Sets.newHashSet();

    // getters and setters
}

组.java

@Entity
@Table(name = "groups")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Groups{

    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "group")
    private String group;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "request_id")
    private Requests requests;

    // getters and setters
}

现在在我的服务类中我做了如下所示

List<Requests> allRequests = requestFeignClient.getRequests();
requestRepository.saveAll(allRequests);

request_id外,所有详细信息都保存到数据库中,如下所示。 我的预期组表也如下所示

谁能告诉我为什么request_id没有被保存。

尝试替换这个:

@OneToMany(mappedBy = "id", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

有了这个:

@OneToMany(mappedBy = "requests", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  相关解决方案