Issue
I'm creating a delete api endpoint for my spring boot application. I tried using the delete() and deleteById() methods provided by the JpaRepository. However, whenever I try to delete a concert, using the ConcertEntity or the concertId, the venue entry associated is deleted from the Venues table. How do I prevent deleting reference entities/tables using the JpaRepository?
My current solution is to set the venue to null before deleting the concert entity. My concertRepositroy extends to JpaRepository.
Current Solution in Service Impl
public void deleteConcert(ConcertEntity e){
e.setVenue(null);
this.concertRepository.delete(e);
}
Concert Entity
@Entity
@Table(name = "CONCERTS")
public class ConcertEntity{
@Id
private UUID concertId;
@Column(name = "ARTIST")
String artist;
@Column(name = "VENUE_ID")
VenueEntity venue;
/*Getters && Setters here...*/
}
Solution
Use the proper annotation to define the relationship (@ManyToOne or @OneToOne)
@ManyToOne(optional = true)
@JoinColumn(name = "VENUE_ID")
private VenueEntity venue;
That should not trigger any cascade deletion by default, but you can add the cascade parameter to the @ManyToOne or @OneToOne annotation if you want to customize the behavior.
Answered By - Santiago Medina
Answer Checked By - Candace Johnson (JavaFixing Volunteer)