0

So I have a schedule object,which contains a list of DateActiveScheduleItems.I want it so that if I remove a DateActiveScheduleItems item from the list in a schedule object and save that schedule using CrudRepository it removes the DateActiveScheduleItem from the database,at the moment my code does not seem to do that.How should I alter the cascade ?

@Entity
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

@ManyToOne
@JoinColumn(name = "usergroup_id")
private UserGroup userGroup;

private String description;


private boolean master;//is this a schedule for all supervalus(true) or one supervalu(false)

@OneToMany(mappedBy = "schedule",cascade = CascadeType.ALL)
private List<DateActiveScheduleItem> dateActiveScheduleItems = new ArrayList<>();

@OneToMany(mappedBy = "schedule",cascade = CascadeType.PERSIST)
private List<MusicScheduleItem> musicScheduleItems = new ArrayList<>();

@OneToMany(mappedBy = "schedule",cascade = CascadeType.PERSIST)
private List<AdvertisementScheduleItem> advertisementScheduleItems = new ArrayList<>();

@Basic
@Temporal(TemporalType.DATE)
private java.util.Date dateAdded;
public Long getId() {
    return id;
 //getters setters
}

DateActiveScheduleItem

@Entity
public class DateActiveScheduleItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Basic
@Temporal(TemporalType.DATE)
private Date date;



@JsonIgnore
@ManyToOne
@JoinColumn(name = "schedule_id")
private Schedule schedule;
//getters setters}
Daniel Haughton
  • 1,085
  • 5
  • 20
  • 45

1 Answers1

0

Orphan Removal removes corresponding child when you remove it from the relationships. So, if you delete 1 DateActiveScheduleItem from dateActiveScheduleItems collection, JPA automatically removes that DateActiveScheduleItem from database too.

@OneToMany(mappedBy = "schedule",cascade = CascadeType.ALL, orphanRemoval="true")
private List<DateActiveScheduleItem> dateActiveScheduleItems = new ArrayList<>();

More on OrphanRemovel HERE

Emil Hotkowski
  • 2,233
  • 1
  • 13
  • 19
  • Getting an error of " A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance" if you happen to know whats going on there,I will post a question on it but I have to wait until the 90 min timer runs out – Daniel Haughton Apr 27 '18 at 08:06
  • I haven't used this type of cascade. I always used orphanRemoval parameter. Here are someone with same problem as yours. https://stackoverflow.com/questions/5587482/hibernate-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenc – Emil Hotkowski Apr 27 '18 at 08:09