Search code examples
javaspringhibernateexceptionjava-ee-6

Throwing user defined exception class from dao layer?


I am using Spring3 and Hibernate4. I have below interface and classes.

FetchDao.java

public interface FetchDao{
  List<FetchEntity> getOrderList(Integer orderNumber);
}

FetchDaoImpl.java

public class FetchDaoImpl implements FetchDao{

   @Autowired
   private SessionFactory sessionFactory; //sessionFactory is injected through spring

   @Override
    public List<FetchEntity> getOrderList(Integer orderNumber) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
                FetchEntity.class);
        criteria.add(Restrictions.eq("orderNumber", orderNumber));
        return criteria.list();
    }

}

Now above configuration works fine without any issues. I have placed them in DAO layer. Above method does not throw any exception. But is it good practice to throw user defined exception always? as below:-

FetchDao.java

public interface FetchDao{
  List<FetchEntity> getOrderList(Integer orderNumber) **throws CustomDAOException**;
}

FetchDaoImpl.java

public class FetchDaoImpl implements FetchDao{

   @Autowired
   private SessionFactory sessionFactory; //sessionFactory is injected through spring

   @Override
    public List<FetchEntity> getOrderList(Integer orderNumber) **throws CustomDAOException**{
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
                FetchEntity.class);
        criteria.add(Restrictions.eq("orderNumber", orderNumber));
        return criteria.list();
    }

}

Here CustomDAOException is user defined exception.

Thanks!


Solution

  • Yes it is good to throw user-defined exception from dao layer,so that your code can get more modularity.