DAO 接口/实现拆分层次结构和约定



在尝试实现基本的通用CRUD DAO时,我遇到了似乎有点反模式的情况

通用道

public interface GenericDao<T, PK extends Serializable> {
  T findOne(final PK id);
  List<T> findAll();
  PK create(final T entity);
  void update(final T entity);
  void delete(final T entity);
  void deleteById(final PK id);
}

泛型道冬眠

public abstract class GenericDaoHibernateImpl<T, PK extends Serializable> implements    GenericDao<T, PK> {
  @Autowired
  private SessionFactory sessionFactory;
  private Class<T> clazz;
  public GenericDaoHibernateImpl(Class<T> clazzToSet) {
      this.clazz = clazzToSet;
  }
  protected final Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
  }
  @Override
  public T findOne(PK id) {
    return (T) getCurrentSession().get(clazz, id);
  }
  @Override
  public List<T> findAll() {
    return getCurrentSession().createQuery("from " + clazz.getName()).list();
  }
  @Override
  public PK create(T entity) {
    return (PK) getCurrentSession().save(entity);
  }
  @Override
  public void update(T entity) {
    getCurrentSession().update(entity);
  }
  @Override
  public void delete(T entity) {
    getCurrentSession().delete(entity);
  }
  @Override
  public void deleteById(PK id) {
    final T entity = findOne(id);
    delete(entity);
  }
}

客户道

public interface CustomerDao extends GenericDao<Customer, Long> {
  public Customer findByUsername(String username);
}

客户DaoHibernateImpl

public class CustomerDaoHibernateImpl extends GenericDaoHibernateImpl<Customer, Long> implements CustomerDao {
  public CustomerDaoHibernateImpl() {
    super(Customer.class);
  }
  public Customer findByUsername(String username);
    Criteria criteria =  getCurrentSession().createCriteria(Customer.class);
    criteria.add(Restrictions.eq("username", username));
    return criteria.list();
  }
}

我所指的问题是,在我们特定领域的DAO实现中,就像我们两次满足/实现泛型道一样。一次在GenericDaoHibernateImpl中,然后再次在我们的域DAO接口中,即CustomerDao。这里我们必须在声明中指定,要使用客户和长。然后我们实现 CustomerDaoHibernateImpl,并且我们必须再次声明 Customer 和 Long。

我做错了什么吗,因为这似乎不是正确的方法。

谢谢

我从未将其视为接口和抽象类扩展/实现共同祖先的反模式。 对我来说,客户界面说它需要通用 dao 中定义的所有操作。抽象类恰好说它实现了通用的 dao。然后,当你到达你的客户 dao impl 时,你表示你实现了客户接口,然后选择通过扩展抽象类来实现它。这允许抽象类和客户接口分别增长或更改,如果其中一个不想扩展/实现通用 dao,但另一个想要。希望这是有道理的

更新:我看到我没有完全回答您的泛型问题,以冗余指定,但希望我的答案为具有相同祖先接口的接口和抽象类提供一些可信度

检查此 http://www.ibm.com/developerworks/java/library/j-genericdao/index.html

最新更新