首先是接口:
package com.sms.dao.base; import java.util.List; public interface BaseDao<T> { public void add(T entity) throws Exception; public void delete(T entity) throws Exception; public void update(T entity) throws Exception; public T findById(Integer id) throws Exception; /* * 得到从startIndex开始大小为pageSize的列表 */ public List<T> getPageList(int startIndex , int pageSize) throws Exception; /* * 得到总数 */ public long getAmount(); }
然后是实现类:
package com.sms.dao.base.impl; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.sms.dao.base.BaseDao; public class BaseDaoImpl<T> implements BaseDao<T> { private Class<T> entityClass; private String hql; @Resource private SessionFactory sessionFactory; public Session getSession(){ return sessionFactory.getCurrentSession(); } @SuppressWarnings("unchecked") public BaseDaoImpl() { //通过反射获取泛型传过来的类的类对象 this.entityClass = (Class<T>) ((ParameterizedType) this.getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; this.hql = "from " + this.entityClass.getName(); } @Override public void add(Object entity) { this.getSession().save(entity); } @Override public void delete(Object entity) { this.getSession().delete(entity); } @Override public void update(Object entity) { this.getSession().update(entity); } @Override public T findById(Integer id) { @SuppressWarnings("unchecked") T result = (T) this.getSession().get(entityClass,id); return result; } @Override public List<T> getPageList(int startIndex, int pageSize) { // TODO Auto-generated method stub @SuppressWarnings("unchecked") List<T> list = this.getSession().createQuery(hql).setFirstResult(startIndex).setMaxResults(pageSize).list(); System.out.println(hql); return list; } @Override public long getAmount() { String sql = "select count(*) from "+ this.entityClass.getName(); long count = (Long) this.getSession().createQuery(sql).uniqueResult() ; return count; } }
通用接口完成,我们使用的时候,只要继承BaseDaoImp就可以实现最基本的增删改查了。
例如学生管理系统中的年级:
接口是:
package com.sms.dao; import com.sms.dao.base.BaseDao; import com.sms.entity.GradeEntity; public interface GradeDao extends BaseDao<GradeEntity>{ }
实现类:
package com.sms.dao.impl;
import org.springframework.stereotype.Component;
import com.sms.dao.GradeDao;
import com.sms.dao.base.impl.BaseDaoImpl;
import com.sms.entity.GradeEntity;
@Component
public class GradeDaoImpl extends BaseDaoImpl<GradeEntity> implements GradeDao{
}
这样子,GradeDaoImpl就可以实现最基础的增删改查的功能了。
转载地址:http://blog.csdn.net/kklt21cn/article/details/42040597