Question

I have the following classes:

public interface GarageRepository extends PagingAndSortingRepository<Garage, Integer> {}

public class GarageBO {
  private GarageRepository garageRepository;

  public void updateGarage(Garage garage) {
    try {
      garageRepository.save(garage);
    } catch (Exception e) {
      throw BoozinaExceptions.getCodeException(garage, e);
    }
  }
}

public class GarageFacade implements GarageService {
  private GarageBO garageBO;

  @Transactional
  public void updateGarage(Garage garage) {
    garageBO.updateGarage(garage);
  }
}

Supposing that i'm trying to update a garage and an unique violation is throwed.
When i call updateGarage from GarageFacade with the @Transactional annotation, garageRepository doesn't throws any exception.
When i call the same method without the @Transactional annotation, garageRepository throws the unique violation exception and now i can convert the exception using BoozinaExceptions.getCodeException(garage, e);

This behavior happens because when i have the @Transactional annotation, the exception will be throwed when Spring jpa data execute the commit. This happens after GarageBO.updateGarage execution ok ?

But i need to convert the unique violation. How can i do that ?
How to handle spring exception after commit then convert to my exception ?

Was it helpful?

Solution

What you describe is the expected behavior. The transaction is committed after the method ends, the commit leads to the unique constraint violation.

Adding @Transactional to the service methods makes the transaction end after the call to the service method the transaction is committed. Removing it makes the transaction commit after the call to the repository method.

Also why do you have a BO a Facade and a Repository?! Basically the BO and Facade are the same IMHO.

TO fix your your problem have your GarageRepository extend JpaRepository instead of PagingAndSortingRepository and call the saveAndFlush method instead of save. This will execute the sql (not committing the transaction) and trigger a constraint violation exception.

Another solution is to instead of doing a try/catch in your BO create and Aspect which does the conversion. Saves you coding the try/catch each time you need it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top