[英]Spring JPA relationships
我在 Spring JPA 关系方面遇到了一些麻烦。
我有两个实体:礼物和糖果。 我希望用户能够 select 可用糖果并将其添加到礼物中。
如何使用 spring jpa 做到这一点?
我已经尝试过将礼物作为拥有方的“一对多”关系,并且在创建和保存糖果时出现“'gift_id 列中的空值违反非空约束'”错误。 这是我的代码:
赠品 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 属性来指定用于映射关系的字段。
@OneToMany(mappedBy = "gift", cascade = CascadeType.ALL, orphanRemoval = true) private List<Candy> candyList = new ArrayList<>();
@ManyToOne() private Gift gift;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.