Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Data-Jpa save: Related entities saved as null which are not

I have an entity timetable:

@Entity @Table(name = TableUtils.TIMETABLE)public class Timetable {

private static final long serialVersionUID = -1307879048598194633L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = ColumnUtils.ID)
private long id;

@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
private List<TimetableCell> timetableCells;

public List<TimetableCell> getTimetableCells() {
    return timetableCells;
}

public void setTimetableCells(List<TimetableCell> timetableCells) {
    this.timetableCells = timetableCells;
}
}

and an entity timetableCell:

@Entity
@Table(name = TableUtils.TIMETABLE_CELL)
public class TimetableCell extends AbstractElement {

private static final long serialVersionUID = -8083688091896353882L;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.WEEK_DAY_ID, nullable = false)
private WeekDay weekDay;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.LESSON_HOUR_ID, nullable = false)
private LessonHour lessonHour;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = ColumnUtils.TIMETABLE_ID, nullable = false)
private Timetable timetable;

...
}

At first I create timetable cells with weekDay and LessonHours. After I set this list to timetable and try to save it. But All timetable cells are saved with null weekDay and null LessonHour. I debugged it. Before save all fields are set as well.

timetableRepository.save(timetable);

Debug result showing following

like image 766
Nəriman Nəhmədov Avatar asked Jan 26 '26 02:01

Nəriman Nəhmədov


2 Answers

1) The timetableCells are marked with only these cascade types:

@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})

2) The week and hour deps have only this:

@ManyToOne(cascade = CascadeType.PERSIST)

3) If you pass Timetable to save method here and it has been persisted before:

timetableRepository.save(timetable);

Spring Data JPA will not call persist, but merge instead.

That might be the case why the cascading does not work. If you add this to your config you might get what you need:

cascade = {CascadeType.REMOVE, CascadeType.PERSIST, CascadeType.MERGE})
like image 60
Maciej Kowalski Avatar answered Jan 28 '26 15:01

Maciej Kowalski


I removed Cascade.Persist from fields in TimetableCell. It works for me but I don't know that what was problem.

like image 39
Nəriman Nəhmədov Avatar answered Jan 28 '26 14:01

Nəriman Nəhmədov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!