How to check, throw and catch a bean validation ConstraintViolationException

Consider the following case:

  • I have a module "serivce" that has a class called ClientService.

  • This one ClientServiceuses the class ClientDaoin the dao module.

  • ClientDaohas a method insert(@Valid Client c). This method calls DaoException.

  • The client is my face. Its attributes are annotated using javax bean validation, for example @javax.validation.constraints.NotNull.

If any restriction is violated, ClientServicereceives ConstraintViolationException. But ClientServiceonly DaoExceptionor any other dao module exception is expected. And I want to save it this way, throwing exceptions related only to the task performed by the object, hiding implementation details for a higher level (in this case, the “service” module).

I would like to do encapsulation javax.validation.ConstraintViolationExceptionin ValidationExceptionmy "dao" module and declare it in a sentence trowsalong with DaoException. And I don't want to do validation checks myself (so I use annotation @Valid)

here is the code (abstracting interfaces, injections and everything else) to make it simple)

package service;

class ClientService {
    insert(Client c) throws ServiceException {
        try {
            new ClientDao().insert(c);
        } catch( DaoException e) {
            throw new ServiceException(e);
        }
    }
}

package dao;

class ClientDao {
    insert(@Valid Client c) throws DaoException {
        myEntityManagerOrAnyPersistenceStrategy.insert(c);
    }
}

I would like to change the dao class to something like:

package dao;

class ClientDao {
    insert(@Valid Client c) throws DaoException, MyValidationException {
        myEntityManagerOrAnyPersistenceStrategy.insert(c);
    }
}

But I do not know how to do this, as I described.

FTR, Spring Web Flow Hibernate . dao @Repository, @Service.

+3
1

, - , , -, @Valid.

, ConstraintViolationException DAO:

class ClientDao {
    insert(@Valid Client c) throws DaoException, MyValidationException {
        try {
            myEntityManagerOrAnyPersistenceStrategy.insert(c);
        } catch (ConstraintViolationException ex) {
            throw new MyValidationException(...);
        }
    }
}
+1

Source: https://habr.com/ru/post/1794311/


All Articles