泛型DAO的设计模式

(一)首先定义DAO接口IGenericDAO,该接口定义了共同的CRUD操作:

public interface IGenericDAO<T,PK extends Serializable>{

              public T findById(PK id) ;

              public List<T> findAll() ;

              public T save(T entity) ;

              public void delete(T entity) ;

             public void update(T entity) ;

}

(二)针对IGenericDAO接口的Hibernate实现,完成通用的CRUD操作

public class GenericDaoHibernate<T,PK extends Serializable> implements IGenericDAO<T,PK>{

              private Class<T> clazz ;

              private Session session ;

              public GenericDaoHibernate(){}

              public T findById(PK id) {

                    return (T)session.get(clazz,id) ;

            }

              public List<T> findAll() {

                       Query query = session.createQuery("from "+clazz.getName()) ;

                       return query.list() ;

            }

              public T save(T entity) {

                        return (T)session.save(entity) ;

 

            }

              public void delete(T entity) {

                      session.delete(entity) ;

           }

              public void update(T entity) {

                       session.update(entity) ;

          }

}

 

(三)举例定义一个IUserDAO接口,该接口继承IGenericDAO

public interface IUserDAO  extends IGenericDAO〈User,Integer〉{

       public User findByName(String username);

}

(四)针对IUserDAO 的Hibernate实现UserDAOHibernate

public class UserDAOHibernate extends GenericDaoHibernate<User,Integer> implements IUserDAO{

..............

}

posted on 2010-12-20 14:03  草原和大树  阅读(2781)  评论(0编辑  收藏  举报