hibernate 4 基础dao 接口 import java.io.Serializable;import java.util.Collection;import java.util.Iterator;import java.util.List;/** * Hibernate基础Dao * @date 2012-6-24 下午4:46:55 * @version 2.0 */public interface HibernateDao {/*
import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Hibernate基础Dao * @date 2012-6-24 下午4:46:55 * @version 2.0 */ public interface HibernateDao { /** * 删除 * @param entity */ publichibernate 4 基础dao 接口实现void delete(T entity); /** * 批量删除 * @param clazz * @param ids */ public void delete(Class clazz, Object[] ids); /** * Execute an HQL query. * @param queryString * @return */ public List find(String queryString); /** * Execute an HQL query. * @param bean * @return */ public List find(Class bean); /** * 批量修改或删除 * @param queryString * @param values */ public int bulkUpdate(String queryString, Object[] values); /** * 批量删除 * @param entities */ public void deleteAll(Collection entities); /** * Execute an HQL query, binding a number of values to "?" * @param queryString * @param values * @return */ public List find(String queryString, Object[] values); /** * 获取唯一实体 * @param queryString HQL query string * @param params query object array params * @return unique object * @see org.hibernate#Session * @throws java.lang.IllegalArgumentException if queryString is null */ public T findUniqueEntity(String queryString, Object ... params); /** * 多条件分页查询 * @param hql query string * @param startRow begin row * @param pageSize page number * @param params query object params array * @return the query list result * @see org.hibernate#Session * @throws java.lang.IllegalArgumentException if queryString is null */ public List findByPage(String queryString, Integer startRow, Integer pageSize, Object... params); /** * Execute a named query. * @param queryName * @return */ public List findByNamedQuery(String queryName); /** * Execute a named query binding a number of values to "?" * @param queryName * @param values * @return */ public List findByNamedQuery(String queryName, Object... values); /** * 获取单个实体 * @param entityClass * @param id * @return */ public T get(Class entityClass, Serializable id); /** * Execute a query for persistent instances. * @param queryString * @return */ public Iterator iterate(String queryString); /** * 条件查询返回一个迭代器 * @param queryString * @param values * @return */ public Iterator iterate(String queryString, Object ... values); /** * load获取一个实体 * @param entityClass * @param id * @return */ public T load(Class entityClass, Serializable id); /** * 持久化一个对象 * @param entity */ public void persist(T entity); /** * 刷新一个对象 * @param entity */ public void refresh(T entity); /** * 保存一个对象 * @param entity * @return */ public Serializable save(T entity); /** * 保存一个集合 * @param entities */ public void saveAll(Collection entities); /** * 保存或修改一个实体 * @param entity */ public void saveOrUpdate(T entity); /** * 保存或修改一个集合 * @param entities */ public void saveOrUpdateAll(Collection entities); /** * 修改一个实体 * @param entity */ public void update(T entity); /** * 修改一个集合 * @param entities */ public void updateAll(Collection entities); /** * id对应的对象是否存在 * @param c * @param id * @return */ public boolean exist(Class c, Serializable id); /** * 统计总条数 * @param hql * @return */ public Integer count(String hql); /** * 根据条件统计总条数 * @param hql * @param obj * @return */ public Integer count(String hql, Object ... obj); /** * 多条件分页查询 * @param queryString HQL语句 * @param startRow 开始行数 * @param pageSize 页数 * @param params 参数集合 * @return 分页查询结果 * @see #findByPage(String, Integer, Integer, Object...) */ public List findByPage(String queryString, PageModel pageModel, List params); }
import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Id; import org.apache.commons.lang3.StringUtils; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; /** * Hibernate4基础DAO实现类 * @date 2012-6-24 下午 4:47:27 * @version 2.0 */ @SuppressWarnings("unchecked") public class HibernateDaoImpl implements HibernateDao { private SessionFactory sessionFactory; /** 获取Hibernate4 Session */ private Session getSession(){ return sessionFactory.getCurrentSession(); } /** * 批量删除 * @param clazz * @param ids */ public分页实体void delete(Class clazz, Object[] ids){ StringBuilder hql = new StringBuilder(); hql.append("delete from " + clazz.getSimpleName()); /** 获取所有的字段 */ Field[] fields = clazz.getDeclaredFields(); /** 定义主键列的属性 */ Field idField = null; /** 循环去获取主键列对应属性 */ for (Field field : fields){ /** 判断字段上面是不是加@Id注解 */ Id id = field.getAnnotation(Id.class); /** 如果不为空,那就是主键列 */ if (id != null){ idField = field; } } hql.append(" where "+ idField.getName() +" in("); for (int i = 0; i < ids.length; i++){ hql.append(i == 0 ? "?" : ",?"); } hql.append(")"); this.bulkUpdate(hql.toString(), ids); } /** * 统计总条数 * @param hql 查询语句 */ @Override public Integer count(final String hql) { if (StringUtils.isEmpty(hql)){ throw new IllegalArgumentException("hql is null"); } Object result = getSession().createQuery(hql).uniqueResult(); return ((Long)result).intValue(); } /** * 批量修改或删除 * @param queryString * @param values */ public int bulkUpdate(String queryString, Object[] values){ Query query = getSession().createQuery(queryString); for(int i = 0; i < values.length; i++){ query.setParameter(i, values[i]); } try{ return query.executeUpdate(); }catch(Exception ex){ throw new RuntimeException(ex); } } /** * 批量删除 * @param entities */ public void deleteAll(Collection entities){ for (T obj : entities){ getSession().delete(obj); } } /** * 按条件统计总条数 * @param hql * @param obj */ @Override public Integer count(final String hql,final Object... obj) { if (ObjectUtils.isEmpty(obj)){ return count(hql); }else{ if (StringUtils.isEmpty(hql)){ return this.count(hql); } Query query = getSession().createQuery(hql); for (int i = 0; i < obj.length; i++) { query.setParameter(i, obj[i]); } Object result = query.uniqueResult(); return ((Long)result).intValue(); } } /** * 删除 * @param entities */ @Override public void delete(T entity) { getSession().delete(entity); } /** * 判断是否存在 * @param entities */ @Override public boolean exist(Class c, Serializable id) { if (get(c, id) != null) return true; return false; } /** * 查询全部 * @param entities */ @Override public List find(String queryString) { return getSession().createQuery(queryString).list(); } /** * Execute an HQL query. * @param bean * @return */ @Override public List find(Class bean){ String hql = "FROM " + bean.getSimpleName(); return find(hql); } /** * 按条件查询全部 * @param queryString * @param values */ @Override public List find(String queryString, Object[] values) { if (ObjectUtils.isEmpty(values)){ return find(queryString); }else{ Query query = getSession().createQuery(queryString); for (int i = 0; i < values.length; i++){ query.setParameter(i, values[i]); } return query.list(); } } /** * 获取唯一实体 * @param queryString HQL query string * @param params query object array params * @return unique object * @see org.hibernate#Session * @throws java.lang.IllegalArgumentException if queryString is null */ @Override public T findUniqueEntity(final String queryString, final Object ... params){ if (StringUtils.isEmpty(queryString)){ throw new IllegalArgumentException("queryString is null"); } if (ObjectUtils.isEmpty(params)){ return (T)getSession().createQuery(queryString).uniqueResult(); }else{ Query query = getSession().createQuery(queryString); for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } return (T)query.uniqueResult(); } } /** * 命名查询 * @param queryName */ @Override public List findByNamedQuery(String queryName) { if (StringUtils.isEmpty(queryName)){ throw new IllegalArgumentException("queryName is null"); } return getSession().getNamedQuery(queryName).list(); } /** * 条件命名查询 * @param queryName * @param values */ @Override public List findByNamedQuery(String queryName, Object... values) { if (ObjectUtils.isEmpty(values)){ return this.findByNamedQuery(queryName); } Query query = getSession().getNamedQuery(queryName); for (int i = 0; i < values.length; i++){ query.setParameter(i, values[i]); } return query.list(); } /** * 多条件分页查询 * @param hql query string * @param startRow begin row * @param pageSize page number * @param params query object params array * @return the query list result * @see org.hibernate#Session * @throws java.lang.IllegalArgumentException if queryString is null */ @Override public List findByPage(String hql, Integer startRow, Integer pageSize, Object ... params) { if (StringUtils.isEmpty(hql)){ throw new IllegalArgumentException("hql is null"); } if (ObjectUtils.isEmpty(params)) { return getSession().createQuery(hql).setFirstResult(startRow) .setMaxResults(pageSize).list(); }else { Query query = getSession().createQuery(hql); for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } return query.setFirstResult(startRow).setMaxResults( pageSize).list(); } } /** * 获取一个实体 * @param entityClass * @param id */ @Override public T get(Class entityClass, Serializable id) { return (T)getSession().get(entityClass, id); } @Override public Iterator iterate(String queryString) { return (Iterator )getSession().createQuery(queryString).iterate(); } @Override public Iterator iterate(String queryString, Object... values) { Query query = getSession().createQuery(queryString); for (int i = 0; i < values.length; i++){ query.setParameter(i, values[i]); } return (Iterator )query.iterate(); } /** * 加载一个实体 * @param entityClass * @param id */ @Override public T load(Class entityClass, Serializable id) { return (T)getSession().load(entityClass, id); } @Override public void persist(T entity) { getSession().persist(entity); } @Override public void refresh(T entity) { getSession().refresh(entity); } /** * 保存 * @param entities * @throws java.lang.IllegalArgumentException if entity is null */ @Override public Serializable save(T entity) { if (entity == null){ throw new IllegalArgumentException("entity is null"); } System.out.println(entity); return getSession().save(entity); } /** * 保存与修改 * @param entities */ @Override public void saveOrUpdate(T entity) { getSession().saveOrUpdate(entity); } /** * 保存与修改全部 * @param entities */ @Override public void saveOrUpdateAll(Collection entities) { for (T obj : entities){ getSession().saveOrUpdate(obj); } } /** * 修改 * @param entity */ @Override public void update(T entity) { getSession().update(entity); } /** * 修改所有的实体 * @param entities * @throws java.lang.IllegalArgumentException if entities is null */ @Override public void updateAll(Collection entities) { if (CollectionUtils.isEmpty(entities)){ throw new IllegalArgumentException("entities is null"); } int i = 0; for (Object obj : entities) { if (i % 30 == 0) { getSession().flush(); getSession().clear(); } getSession().update(obj); i++; } } /** * 保存所有的实体 * @param entities * @throws java.lang.IllegalArgumentException if entities is null */ @Override public void saveAll(Collection entities) { if (CollectionUtils.isEmpty(entities)){ throw new IllegalArgumentException("entities is null"); } int i = 0; for (T obj : entities) { if (i % 30 == 0) { getSession().flush(); getSession().clear(); } save(obj); i++; } } /** * 多条件分页查询 * @param queryString HQL语句 * @param pageModel 分页实体 * @param params 参数集合,没有参数可为NULL * @return 分页查询后集合对象 * @see #findByPage(String, Integer, Integer, List) */ @Override public List findByPage(String queryString, PageModel pageModel, List params){ /** 处理不传where条件只传and的条件查询 (多条件查询时) where 1=1 */ String hql = queryString; if (queryString.toLowerCase().indexOf("where") == -1){ Matcher m = Pattern.compile("and").matcher(queryString); if (m.find()){ hql = m.replaceFirst("where"); }else{ m = Pattern.compile("AND").matcher(queryString); if (m.find()){ hql = m.replaceFirst("WHERE"); } } } // -----------查询总记录条数 int fromIndex = hql.toLowerCase().indexOf("from"); int orderIndex = hql.toLowerCase().indexOf("order"); String hqlCount = "select count(*) " + hql .substring(fromIndex, orderIndex > 0 ? orderIndex : hql.length()); int totalCount = (params == null || params.isEmpty()) ? count(hqlCount) : count(hqlCount, params.toArray()); // 设置总记录条数 pageModel.setRecordCount(totalCount); if(totalCount == 0){ return new ArrayList (); } // -------------分页查询 Object[] temps = (params == null || params.isEmpty()) ? new Object[]{} : params.toArray(); return this.findByPage(hql, pageModel.getStartRow(), pageModel.getPageSize(), temps); } /** Spring4的setter注入 */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
public class PageModel { /** 定义每页显示的数量 */ private final static int PAGE_SIZE = 3; /** 当前页码 */ private int pageIndex; /** 每页显示的数量 */ private int pageSize; /** 总记录条数 */ private int recordCount; public int getPageIndex() { /** 判断当前页码不能小于1 */ this.pageIndex = pageIndex <= 1 ? 1 : pageIndex; /** 当前页面不能大于总页数 */ int totalPage = (this.getRecordCount() - 1) / this.getPageSize() + 1; return pageIndex >= totalPage ? totalPage : pageIndex; } public void setPageIndex(int pageIndex) { this.pageIndex = pageIndex; } public int getPageSize() { return pageSize <= 0 ? PAGE_SIZE : pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getRecordCount() { return recordCount; } public void setRecordCount(int recordCount) { this.recordCount = recordCount; } // limit 第一个? public int getStartRow(){ return (this.getPageIndex() - 1) * this.getPageSize(); } }