HI,
I have a small problem regarding the way Spring handles JPA exceptions
Here is code snippet of my generic DAO :
view plaincopy to clipboardprint?
Code:@Repository public abstract class GenericDaoJpaImpl<T, PK> implements GenericDaoJpa<T, PK> { private static final Logger log = Logger.getLogger(GenericDaoJpaImpl.class); protected Class<T> type = null; @PersistenceContext protected EntityManager em; /** * Empty constructor. The real type T is found with generic reflection */ protected GenericDaoJpaImpl() { this.type = this.getParameterizedType(this.getClass()); } /** * Generic reflection. Find and set generic type used */ @SuppressWarnings("unchecked") private Class<T> getParameterizedType(Class clazz) { Class<T> specificType = null; ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass(); specificType = (Class<T>) parameterizedType.getActualTypeArguments()[0]; return specificType; } ... public T find(PK primaryKey) { log.debug("Search ..."); T entity = em.find(type, primaryKey); // return em.find(type, primaryKey); if (entity == null) { String msg = "The entity'" + type + "' with ID '" + primaryKey + "' was not found ..."; log.debug(msg); // throw new EntityNotFoundException(msg); } return entity; } ... }
And here is a snippet code of a DAO which inherits the generic DAO :
view plaincopy to clipboardprint?
Code:@Repository public class TotoDaoJpaImpl extends GenericDaoJpaImpl<Toto, Long> implements TotoDaoJpa { ... }
And here is the business class in which i inject the TotoDaoJpa DAO which inherits the generic DAO :
view plaincopy to clipboardprint?
Code:public class TotoBusinessImpl implements TotoBusiness { private static final Logger log = Logger.getLogger(TotoBusinessImpl.class); @Resource private TotoDaoJpa totoDao; @Override public void methodFoo(long totoId) throws NotFoundException { ... Toto toto = null; toto = totoDao.find(totoId); ... // This code is not reached if the find(...) method does not find the entity if (null == toto) { blabla } } ... }
The problem is that i do not know which exception to catch when the find(...) method does not find the entity for the totoId parameter.
An exception (does not show in the logs) is thrown but it is either caught or translated by Spring because whenever i try to use the toto variable in a class
in the upper layer i get a ClassCastException : java.lang.String cannot be cast to Toto ...
Whcih exception is thrown by Spring when an entity is not found ?
EmptyResultDataAccessException ?
How do you handle that ?
Thanks.


Reply With Quote
