I have three entities. I want to save a survey. The survey will contain all the data that is neccessary:id,section, questions. The survey_section_question table is created successfully and when I want to retrieve existing data I receive the desired object. I have a problem when I want to save a survey that has sections and questions.I receive the following error:
java.sql.SQLException: Field 'survey_id' doesn't have a default value
Does anyone see what is the error there? I attach the code for the three entities.Thanks in advance for the help!
@Entity
@Table(name="Surveys")
@Data
public class Survey {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private String createdBy;
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(
name = "survey_section_question",
joinColumns = @JoinColumn(name = "survey_id"),
inverseJoinColumns = @JoinColumn(name = "section_id")
)
private List<SurveySection> sections;
}
@Entity
@Table(name="SurveySections")
@Data
public class SurveySection {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@ManyToMany
@JoinTable(
name = "survey_section_question",
joinColumns = @JoinColumn(name = "section_id"),
inverseJoinColumns = @JoinColumn(name = "question_id")
)
private List<SurveyQuestion> questions;
}
@Entity
@Table(name="SurveyQuestions")
@Data
public class SurveyQuestion {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private String createdBy;
private boolean textAnswer;
private boolean gradeAnswer;
}
The sended json:
{"id":1,"name":"mu","description":"sss","createdBy":"xx","sections":[{"id":5,"name":"s2","description":"","questions":[{"id":15,"name":"adawd","description":"awdawd","createdBy":"","textAnswer":true,"gradeAnswer":true}],"selectedQuestion":"15"}]}
The code used for update:
@PutMapping("/{id}")
Survey update(@RequestBody Survey surveyData, @PathVariable Long id) {
return surveyService.findById(id)
.map(survey -> {
survey.setName(surveyData.getName());
survey.setDescription(surveyData.getDescription());
survey.setSections(surveyData.getSections());
survey.setCreatedBy("Test");
return surveyService.save(survey);
})
.orElseGet(() -> surveyService.save(surveyData));
}
The save for the survey service it is just a default call to jpa repository which calls save.
@ManyToMany
associations should be modeled with a Set and not a List. A set will give you much better performance.