2012-04-18 23 views
1

在試圖實現基本通用的CRUD DAO,我遇到了什麼似乎有點反模式DAO接口/實現分層次和公約

GenericDao

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

} 

將GenericDaoHibernateImpl

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

CustomerDao

public interface CustomerDao extends GenericDao<Customer, Long> { 

    public Customer findByUsername(String username); 

} 

CustomerDaoHibernateImpl

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實現,這就像我們滿足/實施GenericDao兩次。一旦進入GenericDaoHibernateImpl,然後再次進入我們的域DAO接口,即CustomerDao。這裏我們必須在聲明中指定使用Customer和Long。 然後我們實現CustomerDaoHibernateImpl,並且我們必須再聲明Customer和Long。

我做錯了什麼,因爲它看起來似乎是正確的方式去了解它。

感謝

+0

一定的可信度這是一個我不相信使用接口定義DAO類的原因。簡化模型的一種方法是刪除CustomerDAO和GenericDAO接口之間的關係。 – Perception 2012-04-18 03:40:19

回答

0

我從來沒有看到它作爲接口和抽象類,延長反模式/實施一個共同的祖先。對我來說,客戶界面表示它需要在通用dao中定義的所有操作。抽象類碰巧說它實現了通用的dao。然後,當你到達你的客戶dao impl時,你指示你實現了客戶界面,然後選擇通過擴展抽象類來實現。這允許抽象類和客戶接口分別增長或更改,如果要麼不想擴展/實現泛型dao,要麼另一個。希望是有道理的

更新:我看到我並沒有完全回答你的問題,仿製藥在具有冗餘地指定,但希望我的回答給了在界面和具有抽象類同一個祖先接口