#I don't like to use @Transactional in methods I like to keep it more micro level

1 messages · Page 1 of 1 (latest)

livid sonnet
#

For the context

what do you think of this?

    @Transactional
    public Customer updateCustomer(Long id, CustomerDTO customerDTO) {
        log.info("Updating customer with ID: {}", id);
        Customer existingCustomer = customerRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Customer not found with ID: " + id));

        modelMapper.map(customerDTO, existingCustomer);
        existingCustomer.setCustomerId(id);

        List<LocationDTO> pickupLocationDTOs= customerDTO.getPickupLocations();
        List<LocationDTO> deliveryLocationDTOs = customerDTO.getDeliveryLocations();

        List<Location> pickupLocations = mapLocations(pickupLocationDTOs, LocationType.PICKUP, existingCustomer);
        List<Location> deliveryLocations = mapLocations(deliveryLocationDTOs, LocationType.DELIVERY, existingCustomer);

        List<Location> allLocations = new ArrayList<>(pickupLocations.size()+deliveryLocations.size());
        allLocations.addAll(pickupLocations);
        allLocations.addAll(deliveryLocations);
        locationRepository.saveAll(allLocations);
        return customerRepository.save(existingCustomer);
    }
formal moonBOT
#

<@&987246399047479336> please have a look, thanks.

hollow jungle
#

Putting a transactional annotation on a method like this is actually a perfect use case

livid sonnet
#

this is just 2 transactions.

hollow jungle
#

I only see a single transaction?

livid sonnet
#

yeah only one trnasaction. what I meant is what if multiple db entry calls

hollow jungle
#

your db can run multiple transactions in parallel as long as you're modifying different rows etc 🙂

#

DBs are awesome

frail shadow
#

Indeed, and we do this at considerable scale. There are a few levers you can pull on a method to indicate whether it needs a transaction, whether it will modify data or could use a readonly transaction, and how it should act if entered without a transaction or in one (creating a new transaction, joining the existing transaction and whether it can elevate a readonly transaction to modify data).

The transaction isolation can be specified to get dirrty-reads, consistent reads or fully serialised transactions (and other nuanced options besides).

Transactions are a fundamental part of concurrent database access.

safe moth
#

transactional, in simplest terms, means "do everything or nothing"

#

if you only have 1 db call, you can omit it, but then you need to be careful with fetching entity relationships because their getters might perform a DB call if they're not fetched already

#

outside of an active transaction that will result in an exception, and even with it, it is uusally better to fetch everying in one DB round trip