I have the following test :
@Test
void checkAddBudgetSum() {
// Arrange
System.out.println("Transaction before update:TransactionSynchronizationManager.isActualTransactionActive())";
BudgetRequest budgetRequest=BudgetRequest.builder().sum(100d).month(12).year(2023).userId("Idan").moneySpent(0d).build();
// Act
try {
budgetRepository.addBudgetSum(budgetRequest);
} catch (Exception e) {
fail("Exception occurred: " +e.getMessage());
}
System.out.println("Transaction after update: " + TransactionSynchronizationManager.isActualTransactionActive());
BudgetData updatedBudget = budgetRepository.findById(1L).get();
// Assert
assertThat(updatedBudget).isNotNull();
assertThat(updatedBudget.getSum()).isCloseTo(200, withinPercentage(0.001));
}
@BeforeEach void setUp() { budgetData=BudgetData.builder().sum(100d).moneySpent(20d).month(12).year(2023).userId("Idan").build(); budgetRepository.save(budgetData); BudgetData savedBudget = budgetRepository.findById(1L).orElse(null); assertThat(savedBudget).isNotNull();}
And it is seems that the budget does not get updated.
This is the repository code for the method:
@Transactional @Modifying @Query("UPDATE BudgetData b " + "SET b.sum = b.sum + :#{#budgetRequest.sum} " + "WHERE b.userId = :#{#budgetRequest.userId} " + "AND b.year = :#{#budgetRequest.year} " + "AND b.month = :#{#budgetRequest.month}") void addBudgetSum(@Param("budgetRequest") BudgetRequest budgetRequest);
According to logging it seems that the sql query that executed should update it:
Hibernate:
update budgets set sum=(sum+cast(? as float(53))) where user_id=? and budget_year=? (I used @Column(name = "budget_year", nullable = false)private int year;) and budget_month=? (I used @Column(name = "budget_month", nullable=false)private int month;)
I've checked and it seems that the problem resides in something that related to Transactions
both here:
System.out.println("Transaction before update: " + TransactionSynchronizationManager.isActualTransactionActive()); and here: System.out.println("Transaction after update: " + TransactionSynchronizationManager.isActualTransactionActive());
I get "true" int both.
I also tried to use EntitiyManager flush method with no success, Tag the method and the class with @Transactional and make sure that I didn't messed up the parameters using :
assertThat(budgetData.getMonth()).isEqualTo(budgetRequest.getMonth()); assertThat(budgetData.getYear()).isEqualTo(budgetRequest.getYear()); assertThat(budgetData.getUserId()).isEqualTo(budgetRequest.getUserId());
that did not show a problem with that.
So If anyone has an advice for me I'll be glad to get it :)