【问题标题】:Throwing user defined exception class from dao layer?从 dao 层抛出用户定义的异常类?
【发布时间】:2013-10-25 09:59:40
【问题描述】:

我正在使用 Spring3 和 Hibernate4。我有以下接口和类。

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();
    }

}

现在上面的配置工作正常,没有任何问题。我已将它们放在 DAO 层中。上面的方法不会抛出任何异常。但是总是抛出用户定义的异常是个好习惯吗?如下:-

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();
    }

}

这里CustomDAOException是用户定义的异常。

谢谢!

【问题讨论】:

    标签: java spring hibernate exception-handling java-ee-6


    【解决方案1】:

    是的,最好从 dao 层抛出用户定义的异常,这样你的代码可以获得更多的模块化。

    【讨论】:

    • 因此,如果抛出任何运行时异常,则在执行方法时,与其发送相同的异常,不如发送用户定义的异常,对吗?谢谢!
    • 是的,通常层(控制器、服务、dao)应该是模块化的(即松散耦合)。所以数据库异常应该在 dao 层并使用 User- 与下一层通信是好的已定义异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 2018-06-04
    • 2011-10-06
    相关资源
    最近更新 更多