由于要求在项目中使用泛型的DAO,所以上网Google了一下,找到了IBM的一篇文章。文章讲得不错,但是有些地方不清楚,如果完全按照那篇文章可能还会遇到一些困难。所以写了这篇文章,解释如何在项目中加入泛型的DAO实现。
首先是总的类关系的UML图:
然后是在配置文件中的关系图:
其中,IStaffDao是我们自己定义的接口,这个接口类似:
public
interface
IStaffDAO
extends
GenericDao
<
Staff, Integer
>
{
public List listAll();
public Staff getByLogonAndId(String logon, Integer id);
// more
}
public List listAll();
public Staff getByLogonAndId(String logon, Integer id);
// more
}
GenericDao<T , PK extends Serilizable> 是泛型的 Dao 接口:
/** */
/**
* 2006-11-22
* 范型DAO接口
* @author Zou Ang
* Contact <a href ="mailto:[email protected]">Zou Ang</a>
*/
public interface GenericDao < T, PK extends Serializable > {
/** */ /**
* 保存一个对象到数据库
* @param newInstance 需要保存的对象
* @return
*/
PK create(T newInstance);
/** */ /**
* 从数据库读取一个对象
* @param id 主键
* @return
*/
T read(PK id);
/** */ /**
* 更新一个对象
* @param transientObject 被更新的对象
*/
void update(T transientObject);
/** */ /**
* 删除一个对象
* @param transientObject 被删除的对象
*/
void delete(T transientObject);
}
* 2006-11-22
* 范型DAO接口
* @author Zou Ang
* Contact <a href ="mailto:[email protected]">Zou Ang</a>
*/
public interface GenericDao < T, PK extends Serializable > {
/** */ /**
* 保存一个对象到数据库
* @param newInstance 需要保存的对象
* @return
*/
PK create(T newInstance);
/** */ /**
* 从数据库读取一个对象
* @param id 主键
* @return
*/
T read(PK id);
/** */ /**
* 更新一个对象
* @param transientObject 被更新的对象
*/
void update(T transientObject);
/** */ /**
* 删除一个对象
* @param transientObject 被删除的对象
*/
void delete(T transientObject);
}
GenericDaoHibernateImpl 是 GenericDao 接口的泛型实现 :
/** */ /**
* 2006-11-22
* 范型DAO实现
* @author Zou Ang
* Contact <a href ="mailto:[email protected]">Zou Ang</a>
*/
public class GenericDaoHibernateImpl < T,PK extends Serializable >
extends HibernateDaoSupport
implements GenericDao < T, PK > ,FinderExecutor {
private Class < T > type;
private FinderNamingStrategy namingStrategy = new SimpleFinderNamingStrategy(); // Default. Can override in config
private FinderArgumentTypeFactory argumentTypeFactory = new SimpleFinderArgumentTypeFactory(); // Default. Can override in config
public GenericDaoHibernateImpl(Class < T > type) {
this .type = type;
}
/**/ /* (non-Javadoc)
* @see com.gdnfha.atcs.common.service.dao.GenericDao#create(java.lang.Object)
*/
public PK create(T newInstance)