1.创建BaseDao接口,抽取公共方法
public interface BaseDao<T> {
//添加
void add(T t);
//修改
void update(T t);
//删除
void delete(T t);
//根据id查询
T findOne(int id);
//查询所有
List<T> listAll();
}
2.创建BaseDaoImpl类实现该接口
3.需要用到公共方法的Dao接口实现BaseDao接口
如CustomerDao Implements BaseDao
4.在该Dao接口实现类中继承BaseDaoImpl
注意:在根据id查询和查询所有语句中,不能直接用泛型T.Class,因此,需要在BaseDaoImpl的构造方法中,得到运行该方法的类Class
//得到当前运行类Class
Class clazz = this.getClass();
//用反射得到父类的参数化类型
Type type = clazz.getGenericSuperclass();
//强转成Type的子接口
ParameteriedType ptype = (ParameterizedType) type;
//根据子接口方法得到实际参数类型
Type[] types = ptype.getActualTypeArguments();
Class pClass = (Class)types[0];