我正在使用 Java Spring Boot。在以下服务功能中:
@Override
public QuestionDTO updateQuestion(Long id, QuestionDTO updateData) {
Question question = questionRepository.findById(id).orElseThrow(() -> new RuntimeException());
if(updateData.getText().length() > 0) {
question.setText(updateData.getText());
}
List<Answer> newAnswers = new ArrayList<>();
// Delete old answers
// some filtering logic that would set isPresent variable
// for i->0 -> arr.size
if(!isPresent) {
Long x = existingAnswer.getId(); // the answer with this id needs to be deleted
answerRepository.deleteById(x);
}
// for i->0 -> arr.size
{
// some logic to update existing answer entity
existingAnswer.setIsCorrect(a.getIsCorrect());
answerRepository.save(existingAnswer);
justUpdate = true;
break;
}
if(!justUpdate) {
a.setQuestion(question);
newAnswers.add(a);
}
LoggingController.getLogger().info("DONE UPDATE! Final array is:");
question.setAnswers(newAnswers);
// Save new array of answers for question
Question updatedQuestion = questionRepository.save(question);
return QuestionMapper.mapToQuestionDTO(updatedQuestion);
}
问题和答案都是实体,我的 PostgreSQL 数据库包含这样的内容:
问题表: |编号 |文字| | -------- | -------------- | | 1 | “法国的首都是什么?” | | 2 | “有多少个国家……”|
答案表: |编号 |文字| Question_id (fk) | 问题ID | -------- | -------------- |-------------------- | | 1 | “答案A” | 1 | | 2 | “答案B”| 1 |
如果我在函数上方使用@Transactional,所有操作都会按其应有的方式执行。但是如果我没有使用这个注解,则不会执行删除操作,其他的则执行。为什么删除不起作用而其他人却起作用?@Transactional的确切效果是什么?
我猜您正在使用 Spring JPA,要了解有关 @transaction 注释的更多信息,请阅读以下内容:链接。 但简而言之,它包装了您的方法,因此它会提交并可以角色返回 JDBC 操作,否则会出现异常。
据我了解,如果你想通过多个更新 存储库,您需要使用 @transactional 注解。