Spring JPA 关系

Spring JPA relationships


我在 Spring JPA 关系方面遇到了一些麻烦。
我有两个实体:礼物和糖果。我希望用户能够 select 可用的糖果并将其添加到礼物中。
我如何使用 spring jpa 来做到这一点?
我已经尝试 'one to many' 与礼物的关系作为拥有方,但在创建和保存糖果时出现“'gift_id violates not-null constraints' 列中的空值”错误。 这是我的代码:
礼物class:

    @Entity
    public class Gift implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;
    private String buyer;

    @OneToMany(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "GiftId", nullable = true)
    private List<Candy> candyList = new ArrayList<>();
    ...

糖果:

    @Entity
    public class Candy implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @JsonIgnore
    private long id;
    private String name;
    private String brand;
    private double price;
    private int weight;
    private int sugar;
    ...

只需使用 mappedBy 属性 指定用于映射关系的字段。

  1. 礼物中

@OneToMany(mappedBy = "gift", cascade = CascadeType.ALL, orphanRemoval = true) private List<Candy> candyList = new ArrayList<>();

  1. 在糖果

@ManyToOne() private Gift gift;