NullConstraint при попытке обновить сущность - PullRequest
0 голосов
/ 12 июня 2019

У меня есть сущность, которая называется семестр. Каждый семестр состоит из нескольких лекций. Поскольку я хотел, чтобы каждая лекция имела оценку, мне пришлось создать дополнительную сущность с именем SemesterLecture. Когда я хочу обновить сущность, я получаю следующий код ошибки:

org.postgresql.util.PSQLException: FEHLER: NULL-Wert в Spalte »semester_id« verletzt Not-Null-Constraint Деталь: Fehlgeschlagene Zeile enthält (0, ноль, ноль).

Вот мой код для обновления сущности семестра:

public Semester editSemester(Semester editSemester, long semesterId) throws NotFoundException {
    LOG.info("Change semester with id " + semesterId);
    if(semesterRepository.existsById(semesterId)){
        LOG.info("Found semester in database");
        Semester existingSemester = semesterRepository.findById(semesterId).get();
        for(SemesterLecture semesterLecture : editSemester.getSemesterLectures()){
            if(!existingSemester.getSemesterLectures().stream().filter(sl -> sl.getLecture().getId().equals(semesterLecture.getLecture().getId())).findFirst().isPresent()){
                LOG.info("Add new lecture...");
                Lecture selectedLecture = lectureRepository.findById(semesterLecture.getLecture().getId()).get();
                SemesterLecture createdSemesterLecture = new SemesterLecture(selectedLecture, semesterLecture.getGrade());
                createdSemesterLecture.setLecture(selectedLecture);
                createdSemesterLecture.setSemester(existingSemester);
                existingSemester.getSemesterLectures().add(createdSemesterLecture);
            }
        }
        LOG.info("Successfully updated all grades");
        return semesterRepository.save(existingSemester);
    }else {
        throw new NotFoundException("Semester with id " + semesterId + " does not exist");
    }
}




public class Semester {
@Id
@GeneratedValue(generator = "semester_generator")
@SequenceGenerator(
        name = "semester_generator",
        sequenceName = "semester_sequence",
        initialValue = 1000
)
private Long id;
private String title;
private int semesterNumber;
@ManyToOne
private Course course;
@OneToMany(mappedBy = "semester", cascade = CascadeType.ALL)
private List<SemesterLecture> semesterLectures = new ArrayList<>();



@Data
@Entity
public class Lecture {
@Id
@GeneratedValue(generator = "lecture_generator")
@SequenceGenerator(
        name = "lecture_generator",
        sequenceName = "lecture_sequence",
        initialValue = 1000
)
private Long id;
private String title;
private int credits;
private int sws;
private String modulNumber;
@OneToMany(mappedBy = "lecture", cascade = CascadeType.ALL)
@JsonIgnore
private List<SemesterLecture> semesterLectures = new ArrayList<>();



@Entity
public class SemesterLecture implements Serializable {
@Id
@ManyToOne
@JsonIgnore
@JoinColumn
private Semester semester;

@Id
@ManyToOne
@JoinColumn
private Lecture lecture;

private String grade;

public SemesterLecture(Lecture lecture, String grade) {
    this.lecture = lecture;
    this.grade = grade;
}

Например, этот код работает:

public Semester changeGradesOfSemesterLectures(long semesterId, Semester semester) throws NotFoundException {
    LOG.info("Change grades of semester with id " + semesterId);
    if(semesterRepository.existsById(semesterId)){
        LOG.info("Found semester in database");
        Semester existingSemester = semesterRepository.findById(semesterId).get();
        for(SemesterLecture semesterLecture : semester.getSemesterLectures()){
            for(SemesterLecture semesterLecture1 : existingSemester.getSemesterLectures()){
                if(semesterLecture.getLecture().getId().equals(semesterLecture1.getLecture().getId())){
                    LOG.info("Change grade of lecture with id " + semesterLecture1.getLecture().getId());
                    semesterLecture1.setGrade(semesterLecture.getGrade());
                }
            }
        }
        LOG.info("Successfully updated all grades");
        return semesterRepository.save(existingSemester);
    }else {
        throw new NotFoundException("Semester with id " + semesterId + " does not exist");
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...