I'm getting really confused with how to map a JPA One to Many Relationship so that I can cascade delete.
I have Yard
@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;
}
And 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;
}
A yard can have many flowers or exist without Flowers but each Flower needs exactly one yard. If a yard gets deleted the flowers should be cascade deleted too. There is a foreign key on Flower for yard_num.
I thought that was OneToMany unidirectional from Yard to Flower. But I'm getting an error putting a OneToMany tag on Yard's yardNum and a @ManyToOne tag on Flower's yardNum. Why do these need to be collections? Also do I have my other tags correct (JoinColumn)?
If Yard can have many Flowers as you mentioned, so the concept is that the entity Yard has to include a collection of entities Flowers (not longs, etc.), maybe empty btw. And the entity Flower must have an entity Yard (not Yard's id)
I'll provide an entities mapping, not tested, but idea is that I mentioned above:
Yard:
@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;
}
Flower:
@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;
}