Search code examples
javaspringhashmapcrudtransactional

How to ensure that each iteration of a HashMap is transactional


I have a method that delete values from a hashmap without deleting the keys.

The structure of the HashMap is as follows, note Kennel and Dog are both Java Objects:

Map<Kennel, List<Dog>> mapOfKennels;

In my method below I am looping through all Kennels and Dogs in my database and deleting dogs (using Crud Repository) from the kennel that have been taken home by an owner (logic for this defined earlier in code).

I only want to delete the dogs from my DB when all or none (i.e. transactional) are removed from a single kennel, i.e. each iteration of the HashMap

Where can I put my @transactional method to do so?

Current Code:

 public void deleteDogsFromKennels(Map<Kennel, List<Dog>> mapOfKennelsAndDogs) {


        //For each Kennel in the Map
        for (Map.Entry<Kennel, List<Dog>> entry : mapOfKennelsAndDogs.entrySet()) {

                String key = entry.getKey().getId();
                List<Dog> dogList = entry.getValue();

                //For each Dog in Kennel
                for (int i = 0; i < dogList.size(); i++) {

                    dogRepository.delete(dogList.get(i));


                }
             }

        }

Solution

  • Refactor your code so that the removal of each kennel is handled by a dedicated method. Then add the @Transactional annotation to this method. For example in DogRepository

    @Transactional
    public class DogRepository{
    
       public void deleteDogs(List<Dog> dogs){
           //delete all dogs
       }
    }
    

    Then in your client code

       public void deleteDogsFromKennels(Map<Kennel, List<Dog>> mapOfKennelsAndDogs) {
        //For each Kennel in the Map
         for (Map.Entry<Kennel, List<Dog>> entry :mapOfKennelsAndDogs.entrySet()){
            String key = entry.getKey().getId();
            List<Dog> dogList = entry.getValue();
            try{
               dogRepository.deleteDogs(dogList);
            }
            catch(Exception ex){
                //log failed to delete kennel with key
             }
         }
       }
    

    Make sure that the deleteDogs method is in a separate class as the deleteDogsFromKennels method otherwise transactions wont work.