Ravi Singh Shekhawat
Ravi Singh Shekhawat

Reputation: 31

Handling Spring Boot JPA exceptions

I'm using Spring boot with JPA in a project. I have a doubt while doing some JPA operation e.g. repository.save(object).

If the program failed to connect DB due to DB is disconnecting intermittently then,

  1. How can the program will retry this with some spring boot feature while exception?
  2. what is the most relevant exception class to be put in class?

Any help is appreciated!

Upvotes: 0

Views: 674

Answers (1)

Rahul Gul
Rahul Gul

Reputation: 582

You have Spring Retry for this specific use case. You can configure on what failure conditions, you would like to retry and there is also a recover method that can be used to recover if the retry fails.

You can enable retry using the @EnableRetry annotation on a configuration class.

@Configuration
@EnableRetry
public class AppConfig { ... } 

And then, use the @Retryable annotation, like this. You can configure on what exceptions you need to retry, on what interval to retry and the number of retries.

@Service
public interface MyService {

    @Retryable(value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000))
    void retryService(String sql) throws SQLException;

}

You can find more details and examples here and the official docs here.

Upvotes: 1

Related Questions