关键字: 通用dao理解, 请大家指正
首先声明我的资料大我来自javaeye,先谢谢各位.
但因本人理解能力不足,现把我对通用DAO的引用贴出,望大家指点.
1.BaseDAO 接口
public interface BaseDAO<T, ID extends Serializable> {
public void save(T entity);
public void delete(T entity);
public T findById(Class<T> entityClass, ID id);
}
2.BaseDAO 的实现
public class BaseHibernateDAO<T, ID extends Serializable> extends HibernateDaoSupport implements BaseDAO<T,ID> {
private static final Logger logger = Logger.getLogger(BaseHibernateDAO.class);
public void save(T entity) {
try {
getHibernateTemplate().save(entity);
} catch (RuntimeException e) {
logger.error("保存实体异常", e);
throw e;
}
}
public void delete(T entity) {
try {
getHibernateTemplate().delete(entity);
} catch (RuntimeException e) {
logger.error("删除实体异常", e);
throw e;
}
}
public void saveOrUpdate(T entity) {
try {
getHibernateTemplate().saveOrUpdate(entity);
} catch (RuntimeException e) {
logger.error("更新或保存实体异常", e);
throw e;
}
}
@SuppressWarnings("unchecked")
public T findById(Class<T> entityClass, ID id) {
try {
return (T) getHibernateTemplate().get(entityClass, id);
} catch (RuntimeException e) {
logger.error("查找指定ID实体异常,ID:" + id, e);
throw e;
}
}
3.一个实体DAO接口extends BaseDAO
public interface ProductDAO extends BaseDAO<Product,Integer>{
//如添加
public void productInsert(Product entity);
public void findById(Product entityClass, Integer id)
//如除crud外Product自己的业务的方法
public void myProductDelete(class clz,Serializable pk);
......
}
4.实体DAO的实现
public class ProductDAOImpl extends BaseHibernateDAO<Product,Integer> implements
ProductDAO {
public void productInsert(Product entity) {
save(entity);
}
public void findById(Class<T> entityClass, ID id) {
findById(entityClass,id);
}
public void myProductDelete(class clz,Serializable pk){
Object object = this.getHibernateTemplate().get(clazz, pk);
this.getHibernateTemplate().delete(object);
}
........
}
5.service层 实体接口
public interface ProductService {
// 添加
public void productInsert(Product entity) throws ProductException;
public void save(Product entity) throws ProductException;
public void delete(Product entity) throws ProductException;
public Product findById(Product entityClass, Integer) throws ProductException;
}
6.service层 实体service实现
public class ProductServiceImpl implements ProductService {
private ProductDAO productDAOImpl;
public void delete(int id) throws ProductException {
try{
productDAOImpl.Delete(productDAOImpl.findproductByPrimaryKey(id));
}catch(Exception e ){
e.printStackTrace();
throw new ProductException(this.getClass().getName()+"Product Delete 删除失败");
}
}
public void save(Product product) throws ProductException {
try{
productDAOImpl.save(product);
}catch(Exception e){
e.printStackTrace();
throw new ProductException(this.getClass().getName()+"Product Insert 添加失败");
}
.......
}
原作者:http://blog.csdn.net/yao_2008/article/details/4258041
引用
请大家帮我看看我这个通用baseDAO的设计是否合理?
具体如:
1.dao的设计有没错?
2.T Class<T>等泛型,反射有没错?
3.service层的传值有没错?
4.这样的异常处理合理吗?
5.就这样的写法是否存在不合理的的写法,而我又不知道的?
各位拍砖吧,至少知道那里不足,继续学习..........