Search code examples
javaspring-bootspring-data-jpatransactionsspring-transactions

Transactional role in Java Spring Boot


I am using Java Spring Boot. In the following service function:

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

Question and Answers are both entities and my PostgreSQL db contains something like this:

Question table:

id text
1 "What is the capital of France?"
2 "How many countries..."

Answer table:

id text question_id (fk)
1 "Answer A" 1
2 "Answer B" 1

If I am using @Transactional above the function, all operations are executed how it should. If I am not using this annotation, the delete operation is not performed, others are. Why the delete is not working and others does and what is the exact effect of @Transactional?


Solution

  • I guess your using Spring data, to get to know more about the @transactional annotation read the following: link. But in short it wraps your method, so it commits and can roll back JDBC operations if there would be an exception.

    From what I understand is that if you want to update through multiple repositories, you need to use the @Transactional annotation (answerRepository / questionRepository).