Search code examples
javadatabasespring-bootservicerepository

Unable to save one-to-many relationship objects in to database. How to save a table list?


Question table:

public class Question {
        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY)
        private Integer id;
        
        @Column
        @NotNull
        private String questionSentence;
    
        @OneToMany(mappedBy = "question",cascade = CascadeType.REMOVE)
        private List<Answers> answers;
        }

Answer table:

public class Answers {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id;
    
    @Column
    @NotNull
    private String answer;
    
    
    
        @ManyToOne 
        @JoinColumn
        @JsonIgnore
        private Question question;
}

I would like to save an answer list in Question that I received from a RequestBody, but it doesent work:

public class QuestionService {
@Autowired
 private QuestionRepository questionRepository;

public ResponseEntity<Question> update
            (Integer questionId,
             Question question) {

Question tempquestion = = questionRepository.findById(questionId);
tempquestion.setAnswers(Question.getAnswers());

 return ResponseEntity.ok(questionRepository.save(tempQuestion));
}

The tempQuestion outputs are working(I get a list from all answers), but the "questionRepository.save(tempQuestion)" doesent save it. (If I want to save other things, like String answer sentence or etc it works, but not if I want to save table list.

What could I do wrong?


Solution

  • If you need to cascade the save operation when the Question entity is saved, so use CascadeType.PERSIST and CascadeType.MERGE on the relationship between Question and Answer entities:

    @OneToMany(mappedBy = "question",cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
        private List<Answers> answers;
    }
    

    or if you want to cascade all operations on Question down to Answer entity, then use:

    @OneToMany(mappedBy = "question",cascade = CascadeType.ALL)
        private List<Answers> answers;
    }