基于泛型的通用Dao接口:(主要是在使用hibernate或JPA时使用)
package com.qiujy.dao;
import java.io.Serializable;
import java.util.List;
/**
* 基于泛型的通用Dao接口
*/
public interface GenericDao<T> {
void create(T entity);
void delete(T entity);
void update(T entity);
T findById(Serializable id);
List<T> findAll();
List<T> findList(int pageNo, int pageSize);
int getCountOfAll();
}
hibernate对此泛型Dao接口的使用:
package com.qiujy.dao.hibernate;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.criterion.Projections;
import com.qiujy.common.HibernateUtil;
import com.qiujy.dao.GenericDao;
/**
* Hibernate对泛型通用Dao接口的实现
*/
public class GenericHibernateDaoImpl<T> implements GenericDao<T> {
private Class<T> clazz;
@SuppressWarnings("unchecked")
public GenericHibernateDaoImpl() {
//通过反射获取T的类型信息实例
this.clazz = (Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
public void create(T entity) {
HibernateUtil.getSession().save(entity);
}
public void delete(T entity) {
HibernateUtil.getSession().delete(entity);
}
@SuppressWarnings("unchecked")
public void update(T entity) {
//HibernateUtil.getSession().saveOrUpdate(entity);
entity = (T) HibernateUtil.getSession().merge(entity);
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return HibernateUtil.getSession().createCriteria(clazz).list();
}
@SuppressWarnings("unchecked")
public List<T> findList(int pageNo, int pageSize) {
return HibernateUtil.getSession().createCriteria(clazz)
.setFirstResult((pageNo - 1) * pageSize)
.setMaxResults(pageSize)
.list();
}
public int getCountOfAll() {
Integer count = (Integer) HibernateUtil.getSession()
.createCriteria(clazz)
.setProjection(Projections.rowCount())
.uniqueResult();
if (null == count) {
return 0;
} else {
return count.intValue();
}
}
@SuppressWarnings("unchecked")
public T findById(Serializable id) {
return (T)HibernateUtil.getSession().load(clazz, id); //get
}
}
使用泛型Dao接口:
package com.qiujy.dao;
import java.util.List;
import com.qiujy.domain.Resource;
/**
* Resource类的Dao接口
*/
public interface ResourceDao extends GenericDao<Resource> {
public List<Resource> findResources(int status);
}
使用hibernate的实现:
package com.qiujy.dao.hibernate;
import java.util.List;
import com.qiujy.common.HibernateUtil;
import com.qiujy.dao.ResourceDao;
import com.qiujy.domain.Resource;
public class ResourceDaoImpl extends GenericHibernateDaoImpl<Resource> implements ResourceDao {
@SuppressWarnings("unchecked")
public List<Resource> findResources(int status) {
return (List<Resource>)HibernateUtil.getSession()
.createQuery("from Resource where status=:status")
.setInteger("status", status)
.list();
}
}
JAVA通用Dao接口和hibernate的实现
最新推荐文章于 2021-02-26 04:20:59 发布