(六)编写基类BaseDao

在action中继承了ActionSupport和其它一些公共属性,如selectedRow等;可能以后还会产生更多公共的内容,所以应该把这些共有的抽取出来,放入到一个基本action中,我们命名为BaseAction,让它去继承ActionSupport和其它公共属性,其它的action只要继承它就可以了。

DAO基类中配备增删改查的操作。

 1 public interface BaseDao<T> {
 2     //新增
 3     public void save(T entity);
 4     //更新
 5     public void update(T entity);
 6     //根据id删除
 7     public void delete(Serializable id);
 8     //根据id查找
 9     public T findObjectById(Serializable id);
10     //查找列表
11     public List<T> findObjects();
12 }
 1 public abstract class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
 2 
 3     Class<T> clazz;
 4     
 5     public BaseDaoImpl(){
 6         ParameterizedType pt =  (ParameterizedType) this.getClass().getGenericSuperclass(); //BaseDaoImpl<user>
 7         clazz = (Class<T>) pt.getActualTypeArguments()[0];
 8     }
 9     
10     public void save(T entity) {
11         getHibernateTemplate().save(entity);
12         
13     }
14 
15     public void update(T entity) {
16         getHibernateTemplate().update(entity);
17         
18     }
19 
20     public void delete(Serializable id) {
21         getHibernateTemplate().delete(findObjectById(id));
22         
23     }
24 
25     public T findObjectById(Serializable id) {
26         
27         return getHibernateTemplate().get(clazz,id);
28     }
29 
30     public List<T> findObjects() {
31         Query query = getSession().createQuery("FROM "+clazz.getSimpleName());
32         return query.list();
33     }
34     
35 }

获取泛型类型:

                   // 使用反射得到T的真实类型

                   ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 获取当前new的对象的 泛型的父类 类型

                   this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; // 获取第一个类型参数的真实类型

         }

原文地址:https://www.cnblogs.com/Michael2397/p/5929131.html