Hi,
I have a question according proper exception handling when using Spring and JPA.
So I have a method for looking for user:
DAO class:Code:@Transactional(readOnly = true) public User findUserByName(String name){ return getUserDAO().findByName(name); }
NoResultFound exception is thrown when username is not found which is translated into org.springframework.dao.EmptyResultDataAccessExcep tion, just like here:Code:public User findByName(String name) { Query query = getEntityManager().createQuery("FROM User user WHERE user.username = :username"); query.setParameter("username", name); return (User) query.getSingleResult(); }
EmptyResultDataAccessException is unchecked, and in my service class I write:HTML Code:Caused by: org.springframework.dao.EmptyResultDataAccessException: No entity found for query at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:295) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:350)
I think that it is a little strange for JPA to throw an exception when something is not found, it's not a good behavior; as far as I know using Hibernate - will not give any exception, and will return null.Code:@Transactional(readOnly = true) public User findUserByName(String name){ User foundedUser = null; try { foundedUser = getUserDAO().findByName(name); } catch (org.springframework.dao.EmptyResultDataAccessException ex) { System.out.println("No Object found"); } return foundedUser; }
Is such handling of exception is correct or not? Should I handle exceptions for other services methods (findyById, update) in the same way?


Reply With Quote