I was wondering the best way the handle the following with EJB3. I have a EJB3 Session Bean which acts as a facade for business activities. In a method, I want to check for existing records and report the error prior to attempting to persist an business object. I am looking for the existance of a database record (say user table with a username field). If the record exists, I return an error that already exists. When I try to find the user record, if not there a EJB3TransactionRollbackException is raised with the cause a NoResultException. I trap the exception but when I try to continue and persist the new record, I get a TransactionRequiredException.
User user = null;
// pseudocode
try {
user = em.findById(username);
// throw already exists exception
}
catch (RuntimeException) ex) {
// test cause and try to continue... desired path
}
if (user == null) {
User user = new User(username);
em.persist(user);
}
It appears that once a exception is raised, you cannot continue. How can I perform the database check and still continue?