我真的很困惑如何映射JPA一对多关系,以便级联删除。
我有庭院
@Data
@Entity
@Table(name = "yard", schema = "example")
public class Yard {
@Id
@OneToMany(cascade= CascadeType.REMOVE, orphanRemoval = true)
@Column(name="yard_num")
long yardNum;
@Column(name="sqft")
Integer sqft;
}
和Flower
@Data
@Entity
@Table(name = "flower", schema = "example")
public class Flower {
@Id
@Column(flower_id)
long flowerId
@ManyToOne(cascade= CascadeType.ALL)
@JoinColumn(name="yard_num")
long yardNum;
@Column(name="num_petals")
Integer numPetals;
}
一个院子可以有很多花,也可以没有花,但每朵花只需要一个院子。如果一个院子被删除,花也应该被级联删除。Flower上有一把用于yard_num的外键。
我以为这是从院子到花儿的单向OneToMany。但我在Yard的yardNum上加了OneToMany标签,在Flower的yardNumber上加了@ManyToOne标签时出错了。为什么这些需要成为收藏品?我的其他标签是否正确(JoinColumn(?
如果Yard可以有许多Flower,正如您所提到的,那么概念是实体Yardlowers(而不是long等(,可能是空的btw。并且实体Flower必须有一个实体Yard(而不是Yard的id(
我将提供一个实体映射,没有测试,但想法是我上面提到的:
堆场:
@Data
@Entity
@Table(name = "yard", schema = "example")
public class Yard {
@Id
@Column(name="yard_num")
Long yardNum;
@OneToMany(mappedBy = "yard", cascade = CascadeType.REMOVE, orphanRemoval = true)
List<Flower> flowers = new ArrayList<>();
@Column(name = "sqft")
Integer sqft;
}
花朵:
@Data
@Entity
@Table(name = "flower", schema = "example")
public class Flower {
@Id
@Column(name="flower_id")
Long flowerId
@ManyToOne
// you have to define FK to table "yard" here, if its name is "yard_num" so it's OK
@JoinColumn(name="yard_num")
Yard yard;
@Column(name="num_petals")
Integer numPetals;
}