'Spring Data JPA flush does not save changes to database

I have the following code that first check record and if found delete that record and flush changes to the database. However, when I debug, I see that it does not reflect changes to the database when debugger hit the next code block (final Stock stock = new Stock();).

@Transactional
public CommandDTO createOrUpdate(StockRequest request) {
    stockRepository.findByBrandUuidAndProductUuid(
                 request.getBrandUuid(), 
                 request.getProductUuid())
            .ifPresent(stock -> {
                stockRepository.delete(stock);
                stockRepository.flush();
            });

    final Stock stock = new Stock();
    if (request.isOutOfStock()) {
        stock.setBrandUuid(request.getBrandUuid());
        stock.setProductUuid(request.getProductUuid());
        stock.save(stock);
    }
    return CommandDTO.builder().uuid(stock.getUuid()).build();
}

So, what is the mistake in this approach?



Solution 1:[1]

JPA doesn't supports final field.

You can use two alternative solution for immutable class.

  1. use @Immutable at entity class.

  2. change entity class fields having only a getter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 seleveal