锁定老帖子 主题:利用JDK5的泛型增强Dao基类
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2006-05-25
DAO:
import java.util.List; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import dao.GenericDAO; import IDSetable; public class GenericDAOIBatis<T, PK> extends SqlMapClientDaoSupport implements GenericDAO<T,PK> { protected String getTname(); { return ""; } @SuppressWarnings("unchecked"); public List<T> selectAll(); { return (List<T>); getSqlMapClientTemplate();.queryForList("selectAll"+getTname();, null);; } public List<T> selectAtRange(PK id, int begin, int end); { // TODO Auto-generated method stub return null; } public void create(T obj); { Object result = getSqlMapClientTemplate();.insert("insert"+getTname();, obj);; if (result != null && obj instanceof IDSetable); { ((IDSetable);obj);.setId(result);; } } @SuppressWarnings("unchecked"); public T get(PK id); { return (T); getSqlMapClientTemplate();.queryForObject("get"+getTname();, id);; } /** * @throws org.springframework.dao.DataAccessException */ public void update(T obj); { getSqlMapClientTemplate();.update("update"+getTname();, obj);; } public void delete(PK id); { getSqlMapClientTemplate();.delete("delete"+getTname();, id);; } } |
|
返回顶楼 | |
发表时间:2006-05-25
子Interface 和 Dao:
public interface TaskDAO extends GenericDAO<Task, Long> { } public class TaskDAOIBatis extends GenericDAOIBatis<Task, Long> implements TaskDAO { @Override protected String getTname(); { return "Task"; } } public interface IDSetable { void setId(Object id);; } |
|
返回顶楼 | |
发表时间:2006-06-23
参考IBM developerWorks的创意:
package com.crackj2ee.dao; import java.util.List; import org.hibernate.Query; public class DaoSupport<T> { private Class<T> type; @SuppressWarnings("unchecked") public T query(Long id) { try { Object obj = getSession().get(type, id); if(obj!=null) return (T)obj; } catch(Exception e) { throw new QueryException("查询失败", e); } throw new QueryException("指定的资源未找到,可能已被删除。"); } public void save(T t) { getSession().save(t); } public void update(T t) { getSession().update(t); } } 我的主键是Long,可以很容易改成别的类型 |
|
返回顶楼 | |