基类接口:package com.lyan.dao;import java.io.Serializable;
import java.util.Collection;/*
 * 封装底层dao有什么好处:
 *  1、实现基本的数据库操作,减少代码量
 *  2、基本操作都通过这一基类,便于维护
 *  3、若基类满足不了用户要求扩展,可通过自身如DepartmentDao进行个性化扩展,延展性强
 */
public interface BaseDao<T> {
public void addEntity(T t);

public void updateEntity(T t);

public void deleteEntity(Serializable id);

public T getEntityById(Serializable id);

public Collection<T> getAllEntitys();
}基类接口实现:package com.lyan.dao.impl;import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;import org.springframework.orm.hibernate3.HibernateTemplate;import com.lyan.dao.BaseDao;public class BaseDaoImpl<T> implements BaseDao<T>{
private HibernateTemplate hibernateTemplate;
private Class classt;

public BaseDaoImpl(){
ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
classt = (Class)pt.getActualTypeArguments()[0];
System.out.println("***********"+pt.getOwnerType()+" , "+pt.getRawType()+"*********");
}

@Override
public void addEntity(T t) {
this.hibernateTemplate.save(t);
} @Override
public void updateEntity(T t) {
this.hibernateTemplate.update(t);
} @Override
public void deleteEntity(Serializable id) {
T t = this.getEntityById(id);
this.hibernateTemplate.delete(t);
} @Override
public T getEntityById(Serializable id) {
return (T)this.hibernateTemplate.get(this.classt, id);
} @Override
public Collection<T> getAllEntitys() {
return this.hibernateTemplate.find("from "+this.classt.getName());
} public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
} public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}具体业务扩展接口:package com.lyan.dao;import com.lyan.bean.Department;/**
 * 这里的DepartmentDao可以不必继承BaseDao,不继承的话就是Service层不能直接访问BaseDao中的方法
 * @author yanlei
 *
 * @param <T>
 */
public interface DepartmentDao<T> extends BaseDao<T>{
//当基类接口不能满足业务,业务要个性化定制时,写在此处进行扩展
}
业务拓展接口的实现:package com.lyan.dao.impl;import com.lyan.bean.Department;
import com.lyan.dao.DepartmentDao;public class DepartmentDaoImpl extends BaseDaoImpl<Department> implements DepartmentDao<Department> {}剩下的就是service层的调用,我就不在写了

解决方案 »

  1.   

    您这是hibernate的,我要springjdbc的通用泛型dao,有吗?最好基类dao封装的完美些,具体业务dao就不需要了
      

  2.   

    基于SpringJdbc的泛型Daohttp://1194867672-qq-com.iteye.com/blog/1455814
      

  3.   

     Could not instantiate bean class [com.hgsoft.dao.impl.PeopleDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class这个问题,用你的方案报出来,是因为我包没导入吗?
      

  4.   

    在笔记本上,公司没有具体代码,晚上回去跟你贴着,Spring JdbcTemplate 写的BaseDao<T> 支持对象查找
      

  5.   

    看看这个,希望对你有帮助 http://www.meiriyouke.net/?p=313