(一)首先定义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{
..............
}
/* 如何得到泛型的class */
this.clazz = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];