Hi all,
Suppose we are implementing the code for "register a new user to Spring forum". And you need to guarantee that username is unique...
(There is a service layer, a dao layer, and a view layer. Using declarative transaction management.)
Here is what i thought:
hmm, i can put a constraint check in database, let Spring throw DataIntegrityViolationException and catch it in the service layer and
wrap it within a more specific and meaningful exception and throw the new exception.
Here is the service layer code:
You might guess what actually happens in this situation; i can't catch the exception, because dao.save(user) would not really save to the databaseCode:@Transactional public void save(User User) { try { dao.save(user); } catch (DataIntegrityViolationException ex) { throw new BusinessException("Duplicate username."); } }
(hence the constraint viloation does not manifest) until transaction commits (when the save method exits).
Any suggestion? What do you think i should do?


Reply With Quote