Vijay Vijay - 5 months ago 97
MySQL Question

Retry after Spring throws DataAccessException not working

I am facing a very peculiar situation. I am using hibernate template with spring 3.0.5 for DB operations. When I try to insert a User model the first time, a DataAccessException is thrown, which I catch. Now I wish to retry the same DB operation for say 3 times. The second time when it, no exception is thrown.

Here is the code:

package com.user.profile.dao;

public class UserProfileDAOImpl implements IUserProfileDAO {

private HibernateTemplate hibernateTemplate;

public Long insertUserProfileData(User user) throws AppNonFatalException {
Long id = null;
int retryCount = 0;

while (retryCount < 3) {
try {
id = (Long);
catch (DataAccessException e) {
System.out.println("Retry Count = " + retryCount);
if (retryCount > 3) {
throw new AppNonFatalException(e.getLocalizedMessage(), "10000", e.getMessage(), e);
catch (Exception e) {
/* not coming inside this block too second time onwards */
System.out.println("Pure Exception");

return id;


I read that RuntimeExceptions should not be caught. Then how do I retry the operation. Should I retry at the service layer? Am I missing something? Any help is appreciated.

Answer Source


Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code.

Since DataAccessException is a RuntimeException, you might want to check what is the real cause of the exception and fix it instead of catching it and retry the operation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download