【问题标题】:Unable to save one-to-many relationship objects in to database. How to save a table list?无法将一对多关系对象保存到数据库中。如何保存表格列表?
【发布时间】:2021-03-29 11:45:22
【问题描述】:

问题表:

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;
        }

答案表:

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

我想在我从 RequestBody 收到的问题中保存一个答案列表,但它不起作用:

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));
}

tempQuestion 输出正常(我从所有答案中得到一个列表),但“questionRepository.save(tempQuestion)”并没有保存它。 (如果我想保存其他东西,比如字符串回答句等,它可以工作,但如果我想保存表格列表,则不行。

我会做错什么?

【问题讨论】:

  • 尝试使用 cascade = CascadeType.ALL

标签: java database spring-boot service repository


【解决方案1】:

如果需要在保存Question实体时级联保存操作,那么在QuestionAnswer实体之间的关系上使用CascadeType.PERSISTCascadeType.MERGE

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

或者如果您想将Question 上的所有操作级联到Answer 实体,则使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2018-07-16
    • 1970-01-01
    相关资源
    最近更新 更多