wadise

BlogJava 首页 新随笔 联系 聚合 管理
  22 Posts :: 0 Stories :: 6 Comments :: 0 Trackbacks
DAO
许多Java开发员已经知道DAO模式。这个模式有许多不同的实现,尽管如此,在这篇文章中将阐述DAO实现的设想:
1.系统中所有数据库访问都通过DAO来包装
2.每个DAO实例代表一个原生的领域对象或实体。如果一个领域对象有一个独立的生命周期,那么它应该有自己的DAO。
3.DAO代表在领域对象上的CURD操作。
4.DAO允许基于Criteria的查询不同于用主键查询。我比较倾向构造一个finder方法。该finder方法的返回值是一个领域对象组的Collection集合
5.DAO不代表处理事务,Sessions或连接。这些在DAO外处理将更加灵活。

例子:
GenericDao是CRUD操作的DAO基类。
public interface GenericDao <T, PK extends Serializable> {

    
/** Persist the newInstance object into database */
    PK create(T newInstance);

    
/** Retrieve an object that was previously persisted to the database using
     *   the indicated id as primary key
     
*/
    T read(PK id);

    
/** Save changes made to a persistent object.  */
    
void update(T transientObject);

    
/** Remove an object from persistent storage in the database */
    
void delete(T persistentObject);
}


下面是它的实现类:
public class GenericDaoHibernateImpl <T, PK extends Serializable>
    
implements GenericDao<T, PK>, FinderExecutor {
    
private Class<T> type;

    
public GenericDaoHibernateImpl(Class<T> type) {
        
this.type = type;
    }

    
public PK create(T o) {
        
return (PK) getSession().save(o);
    }

    
public T read(PK id) {
        
return (T) getSession().get(type, id);
    }

    
public void update(T o) {
        getSession().update(o);
    }

    
public void delete(T o) {
        getSession().delete(o);
    }
}


扩展GenericDAO
public interface PersonDao extends GenericDao<Person, Long> {
    List
<Person> findByName(String name);
}

posted on 2006-06-05 23:10 wadise 阅读(267) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: