开发者

How to check, throw and catch bean's validation ConstraintViolationException

Consider the following case:

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

  • This ClientService uses a class called ClientDao in a "dao" module.

  • ClientDao has a method insert(@Valid Client c). This method throws DaoException.

  • Client is my entity. His attributes are annotated with javax bean validations, like @javax.validation.constraints.NotNull.

If some constraint is violated, ClientService receives a ConstraintViolationException. But ClientService only expects DaoException or any other Exception of the "dao" module. And I want to keep it that way, throwing exceptions only related directly to the task that the object does, hiding implementation details for the higher layer (in that case, the "service" module).

What I would like to do is encapsulate javax.validation.ConstraintViolationException in a ValidationException of my "dao" module, and declare it in the trows clause, alongside with DaoException. AND I don't want to perform the validation checks by myself (that's why I use the @Valid annotation)

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 开发者_Go百科class to something like:

package dao;

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

But I have no idea how to do this in the way I described.

FTR, I'm using Spring Web Flow and Hibernate in this project. The dao module contains @Repository classes and the service module contains @Service classes.


Perhaps I don't understand something, but I guess in your case validation is performed automatically by persistence provider and has nothing to do with your @Valid annotation.

If so, you can simply catch ConstraintViolationException inside your DAO method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜