java-Spring-Data-Jpa保存:保存为null的相关实体不是
作者:互联网
我有实体时间表:
@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;
}
}
和一个实体的时间表单元:
@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;
...
}
首先,我使用weekDay和LessonHours创建时间表单元格.在将此列表设置为时间表并尝试保存之后.但是所有时间表单元格都使用空的weekDay和空的LessonHour保存.
我调试了在保存之前,还设置了所有字段.
timetableRepository.save(timetable);
调试结果显示如下
解决方法:
1)timetableCells仅用以下级联类型标记:
@OneToMany(mappedBy = "timetable", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
2)周和小时部门只有以下几点:
@ManyToOne(cascade = CascadeType.PERSIST)
3)如果您在此处传递时间表以保存方法,并且该方法之前一直存在:
timetableRepository.save(timetable);
Spring Data JPA不会调用持久化,而是合并.
为什么级联不起作用可能是这种情况.如果将其添加到配置中,则可能会得到所需的内容:
cascade = {CascadeType.REMOVE, CascadeType.PERSIST, CascadeType.MERGE})
标签:spring-data-jpa,hibernate,java 来源: https://codeday.me/bug/20191210/2104435.html