Hibernate 通用操作类 BaseHibernateDao
来源:互联网 发布:tensorflow 数据结构 编辑:程序博客网 时间:2024/06/06 09:49
在用HIbernate的时候,写DAO每次都要获取session,query,感觉很繁琐,就自己写了一个类,实现了绝大多数功能,代码简化了很多,话不多说,直接上代码:
BaseHibernateDao类
package cn.util;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.util.HibernateSessionFactory;//session工厂类
import cn.util.PageBean;//分页包装类
/**
* BaseHibernateDao 定义DAO的通用操作的实现
*
* @author hezhao
*
*/
@SuppressWarnings(“unchecked”)
public abstract class BaseHibernateDao {
private Class<T> clazz;/** * 反射 通过构造方法指定DAO的具体实现类 */public BaseHibernateDao() { ParameterizedType type = (ParameterizedType) this.getClass() .getGenericSuperclass(); clazz = (Class<T>) type.getActualTypeArguments()[0]; // System.out.println("DAO的真实实现类是:" + this.clazz.getName());}/** * 查询返回集合 * * @param hql * @param params * @return List */public List<T> queryList(String hql, Object... params) { return prepareQuery(hql, params).list();}/** * 查询返回集合 * * @param hql * @param params * @return List */public List<T> queryList(String hql, Map<Object, Object> params) { return prepareQuery(hql, params).list();}/** * 查询返回集合 * * @param hql * @param params * 封装条件的Map集合 * * @return List */public List<T> queryListByProperties(String hql, Map<String, Object> params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).list();}/** * 查询返回集合 * * @param hql * @param params * 封装条件的对象 * * @return List */public List<T> queryListByProperties(String hql, Object params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).list();}/** * 查询返回单个对象 * * @param hql * @param params * @return */public T queryFirst(String hql, Object... params) { return (T) prepareQuery(hql, params).setMaxResults(1).uniqueResult();}/** * 查询返回单个对象 * * @param hql * @param params * @return */public T queryFirst(String hql, Map<Object, Object> params) { return (T) prepareQuery(hql, params).setMaxResults(1).uniqueResult();}/** * 查询返回单个对象 * * @param hql * @param params * 封装条件的Map集合 * * @return */public T queryFirstByProperties(String hql, Map<String, Object> params) { return (T) HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).setMaxResults(1).uniqueResult();}/** * 查询返回单个对象 * * @param hql * @param params * 封装条件的对象 * * @return */public T queryFirstByProperties(String hql, Object params) { return (T) HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).setMaxResults(1).uniqueResult();}/** * 根据主键查询一条数据,立即查询, 若加载的数据不存在,返回NULL * * @param id * * @return */public T get(Serializable id) { return (T) HibernateSessionFactory.getSession().get(this.clazz, id);}/** * 根据主键查询一条数据,延时加载, 若加载的数据不存在,返回NULL * * @param id * * @return */public T load(Serializable id) { try { return (T) HibernateSessionFactory.getSession() .load(this.clazz, id); } catch (HibernateException e) { e.printStackTrace(); return null; }}/** * 获取数据的数量 * * @param hql * @param params * @return Integer */public Integer getCount(String hql, Object... params) { long count = (Long) prepareQuery(hql, params).setMaxResults(1) .uniqueResult(); return (int) count;}/** * 获取数据的数量 * * @param hql * @param params * @return Integer */public Integer getCount(String hql, Map<Object, Object> params) { long count = (Long) prepareQuery(hql, params).setMaxResults(1) .uniqueResult(); return (int) count;}/** * 获取数据的数量 * * @param hql * @param params * 封装条件的Map集合 * @return Integer */public Integer getCountByProperties(String hql, Map<String, Object> params) { Query query = HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params); long count = (Long) query.setMaxResults(1).uniqueResult(); return (int) count;}/** * 获取数据的数量 * * @param hql * @param params * 封装条件的对象 * @return Integer */public Integer getCountByProperties(String hql, Object params) { Query query = HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params); long count = (Long) query.setMaxResults(1).uniqueResult(); return (int) count;}/** * 投影查询 * * @param hql * @param params * @return */public List Projection(String hql, Object... params) { return prepareQuery(hql, params).list();}/** * 投影查询 * * @param hql * @param params * @return */public List Projection(String hql, Map<Object, Object> params) { return prepareQuery(hql, params).list();}/** * 投影查询 * * @param hql * @param params * 封装条件的Map集合 * @return */public List ProjectionByProperties(String hql, Map<String, Object> params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).list();}/** * 投影查询 * * @param hql * @param params * 封装条件的对象 * @return */public List ProjectionByProperties(String hql, Object params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).list();}/** * 获得唯一结果 * * @param hql * @param params * @return Object */public Object Single(String hql, Object... params) { return prepareQuery(hql, params).setMaxResults(1).uniqueResult();}/** * 获得唯一结果 * * @param hql * @param params * @return Object */public Object Single(String hql, Map<Object, Object> params) { return prepareQuery(hql, params).setMaxResults(1).uniqueResult();}/** * 获得唯一结果 * * @param hql * @param params * 封装条件的Map集合 * @return Object */public Object SingleByProperties(String hql, Map<String, Object> params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).setMaxResults(1).uniqueResult();}/** * 获得唯一结果 * * @param hql * @param params * 封装条件的对象 * @return Object */public Object SingleByProperties(String hql, Object params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params).setMaxResults(1).uniqueResult();}/** * 使用hql 语句进行分页查询操作 * * @param hql * 需要查询的hql语句 * @param params * 如果hql有多个参数需要传入,params就是传入的参数数组 * @param pageIndex * 当前页码 * @param pageSize * 每页需要显示的记录数 * @return 当前页的所有记录 */public List<T> queryForPage(String hql, int pageIndex, int pageSize, Object... params) { return prepareQuery(hql, params) .setFirstResult((pageIndex - 1) * pageSize) .setMaxResults(pageSize).list();}/** * 使用hql 语句进行分页查询操作 * * @param hql * 需要查询的hql语句 * @param params * 如果hql有多个参数需要传入,params就是传入的Map集合 * @param pageIndex * 当前页码 * @param pageSize * 每页需要显示的记录数 * @return 当前页的所有记录 */public List<T> queryForPage(String hql, int pageIndex, int pageSize, Map<Object, Object> params) { return prepareQuery(hql, params) .setFirstResult((pageIndex - 1) * pageSize) .setMaxResults(pageSize).list();}/** * 使用hql 语句进行分页查询操作 参数绑定为条件集合(Map) * * @param hql * 需要查询的hql语句 * @param params * 封装条件的Map集合 * @param pageIndex * 当前页码 * @param pageSize * 每页需要显示的记录数 * @return 当前页的所有记录 */public List<T> queryForPageByProperties(String hql, int pageIndex, int pageSize, Map<String, Object> params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params) .setFirstResult((pageIndex - 1) * pageSize) .setMaxResults(pageSize).list();}/** * 使用hql 语句进行分页查询操作 参数绑定为条件对象 * * @param hql * 需要查询的hql语句 * @param params * 封装条件的对象 * @param pageIndex * 当前页码 * @param pageSize * 每页需要显示的记录数 * @return 当前页的所有记录 */public List<T> queryForPageByProperties(String hql, int pageIndex, int pageSize, Object params) { return HibernateSessionFactory.getSession().createQuery(hql) .setProperties(params) .setFirstResult((pageIndex - 1) * pageSize) .setMaxResults(pageSize).list();}/** * 获取分页对象 * * @param hql * @param params * @param pageIndex * 当前页码 * @param pageSize * 每页显示的数量 * @return PageBean */public PageBean<T> findForPage(String hql, int pageIndex, int pageSize, Object... params) { int totalCount = queryList(hql, params).size(); // 总记录数 List<T> list = queryForPage(hql, pageIndex, pageSize, params); // 把分页信息保存到pageBean中 return new PageBean<T>(list, pageSize, pageIndex, totalCount);}/** * 获取分页对象 * * @param hql * @param params * @param pageIndex * 当前页码 * @param pageSize * 每页显示的数量 * @return PageBean */public PageBean<T> findForPage(String hql, int pageIndex, int pageSize, Map<Object, Object> params) { int totalCount = queryList(hql, params).size(); // 总记录数 List<T> list = queryForPage(hql, pageIndex, pageSize, params); // 把分页信息保存到pageBean中 return new PageBean<T>(list, pageSize, pageIndex, totalCount);}/** * 获取分页对象 * * @param hql * @param params * 封装条件的Map集合 * @param pageIndex * 当前页码 * @param pageSize * 每页显示的数量 * @return PageBean */public PageBean<T> findForPageByProperties(String hql, int pageIndex, int pageSize, Map<String, Object> params) { int totalCount = queryListByProperties(hql, params).size(); // 总记录数 List<T> list = queryForPageByProperties(hql, pageIndex, pageSize, params); // 把分页信息保存到pageBean中 return new PageBean<T>(list, pageSize, pageIndex, totalCount);}/** * 获取分页对象 参数绑定为条件对象 * * @param hql * @param params * 封装条件的对象 * @param pageIndex * 当前页码 * @param pageSize * 每页显示的数量 * @return PageBean */public PageBean<T> findForPageByProperties(String hql, int pageIndex, int pageSize, Object params) { int totalCount = queryListByProperties(hql, params).size(); // 总记录数 List<T> list = queryForPageByProperties(hql, pageIndex, pageSize, params); // 把分页信息保存到pageBean中 return new PageBean<T>(list, pageSize, pageIndex, totalCount);}/** * 新增 * * @param entity * @return boolean */public boolean save(T entity) { Transaction tx = null; try { Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); session.save(entity); tx.commit(); return true; } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } return false; }}/** * 修改 * * @param entity * @return boolean */public boolean update(T entity) { Transaction tx = null; try { Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); session.update(entity); tx.commit(); return true; } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } return false; }}/** * 增加或修改 * * @param entity * @return boolean */public boolean saveOrUpdate(T entity) { Transaction tx = null; try { Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); session.saveOrUpdate(entity); tx.commit(); return true; } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } return false; }}/** * 把一个游离态对象的属性复制到一个持久化对象中,执行更新或插入操作并返回持久化的对像,若传入的是瞬时态对象则保存并返回其副本 * * @param entity * @return */public T merge(T entity) { Transaction tx = null; try { Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); T result = (T) session.merge(entity); tx.commit(); return result; } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } return null; }}/** * 删除 * * @param entity * @return boolean */public boolean delete(T entity) { Transaction tx = null; try { Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); session.delete(entity); tx.commit(); return true; } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } return false; }}/** * 删除 * * @param id * @return boolean */public boolean delete(Serializable id) { Transaction tx = null; try { Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); T entity = get(id); session.delete(entity); tx.commit(); return true; } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } return false; }}/** * 准备query对象 内部调用 * * @param hql * @param params * @return Query */private Query prepareQuery(String hql, Object... params) { Session session = HibernateSessionFactory.getSession(); Query query = session.createQuery(hql); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } } return query;}/** * 准备query对象 内部调用 * * @param hql * @param params * @return QueryS */private Query prepareQuery(String hql, Map<Object, Object> params) { Session session = HibernateSessionFactory.getSession(); Query query = session.createQuery(hql); if (params != null && params.size() > 0) { for (Object key : params.keySet()) { if (key instanceof Integer) { query.setParameter((Integer) key, params.get(key)); } else if (key instanceof String) { query.setParameter((String) key, params.get(key)); } } } return query;}
}
PageBean类
package cn.util;
import java.util.List;
/**
* 分页包装对象(包装分页常用属性)
*
* @author Administrator
*
*/
public class PageBean {
private List list;// 当前页列表数据
private int totalCount;// 总记录数
private int totalPages;// 总页数
private int pageSize = 5;// 每页显示多少条
private int pageIndex = 1;// 当前页码
private int prePageIndex;// 上一页码
private int nextPageIndex;// 下一页码
private int firstPageIndex = 1;// 第一页码
private int lastPageIndex;// 最后一页码
private boolean hasPreviousPage;// 是否有上一页
private boolean hasNextPage;// 是否有下一页
private String pagerString;// 分页导航条
/* * 分页包装对象 */public PageBean() {}/** * PageBean 分页包装对象 * * @param list * 当前页列表数据 * @param pageSize * 每页显示的数量 * @param pageIndex * 当前页码 * @param totalCount * 总记录数 */public PageBean(List<T> list, int pageSize, int pageIndex, int totalCount) { this.setList(list); this.setPageSize(pageSize); this.setPageIndex(pageIndex); this.setTotalCount(totalCount);}/** * 获得当前页列表数据 * * @return List */public List<T> getList() { return this.list;}/** * 设置当前页列表数据 * * @param list * @return PageBean */public PageBean<T> setList(List<T> list) { this.list = list; return this;}/** * 获得总记录数 * * @return int */public int getTotalCount() { return this.totalCount;}/** * 设置总记录数 * * @param totalCount * @return PageBean */public PageBean<T> setTotalCount(int totalCount) { this.totalCount = totalCount; return this;}/** * 总页数 * * @return int */public int getTotalPages() { // 计算出总页数 this.totalPages = (this.totalCount % this.pageSize == 0 ? (this.totalCount / this.pageSize) : (this.totalCount / this.pageSize) + 1); if (this.totalPages < 1) { this.totalPages = 1; } return this.totalPages;}/** * 获得每页显示的数量 * * @return int */public int getPageSize() { return this.pageSize;}/** * 设置每页显示的数量 * * @param pageSize * @return PageBean */public PageBean<T> setPageSize(int pageSize) { this.pageSize = pageSize; return this;}/** * 获得当前页码 * * @return int */public int getPageIndex() { if (this.pageIndex < 1) { this.pageIndex = 1; } if (this.pageIndex > getTotalPages()) { this.pageIndex = getTotalPages(); } return this.pageIndex;}/** * 设置当前页码 * * @param pageIndex * @return PageBean */public PageBean<T> setPageIndex(int pageIndex) { this.pageIndex = pageIndex; return this;}/** * 上一页 * * @return int */public int getPrePageIndex() { this.prePageIndex = this.getPageIndex() - 1; if (this.prePageIndex < 1) { this.prePageIndex = getFirstPageIndex(); } return this.prePageIndex;}/** * 下一页 * * @return int */public int getNextPageIndex() { this.nextPageIndex = this.getPageIndex() + 1; if (this.nextPageIndex > getTotalPages()) { this.nextPageIndex = getTotalPages(); } return this.nextPageIndex;}/** * 首页 * * @return int */public int getFirstPageIndex() { return this.firstPageIndex;}/** * 尾页 * * @return int */public int getLastPageIndex() { this.lastPageIndex = this.getTotalPages(); return this.lastPageIndex;}/** * 是否有上一页 * * @return boolean */public boolean getHasPreviousPage() { this.hasPreviousPage = this.getPageIndex() > 1 ? true : false; return this.hasPreviousPage;}/** * 是否有下一页 * * @return boolean */public boolean getHasNextPage() { this.hasNextPage = this.getPageIndex() < this.getTotalPages() ? true : false; return this.hasNextPage;}/** * 分页导航条 * @return String */public String getPagerString() { // 起始数字 int start = this.getPageIndex() - 5 >= 1 ? this.getPageIndex() - 5 : 1; // 结束数字 int end = this.getTotalPages() - start > 10 ? start + 10 : this .getTotalPages(); StringBuffer sbf = new StringBuffer(); sbf.append("<ul class='pager'>"); // 显示首页和上一页 if (this.getHasPreviousPage()) { sbf.append("<li><a href='javascript:ChangePageIndex(" + this.getFirstPageIndex() + ");'>首页</a></li>"); sbf.append("<li><a href='javascript:ChangePageIndex(" + this.getPrePageIndex() + ");'>上一页</a></li>"); } // 显示数字页码 for (int i = start; i <= end; i++) { if (i == this.getPageIndex()) { sbf.append("<li><font class='currentPageIndex'>" + i + "</font></li>"); } else { sbf.append("<li><a href='javascript:ChangePageIndex(" + i + ");'>" + i + "</a></li>"); } } // 显示下一页和尾页 if (this.getHasNextPage()) { sbf.append("<li><a href='javascript:ChangePageIndex(" + this.getNextPageIndex() + ");'>下一页</a></li>"); sbf.append("<li><a href='javascript:ChangePageIndex(" + this.getLastPageIndex() + ");'>尾页</a></li>"); } sbf.append("</ul>"); this.pagerString = sbf.toString(); return pagerString;}
}
HibernateSessionFactory 类,这个是MyEclise自动生成的,这里一并贴上
package cn.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
/**
*
* Session工厂类
*/
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();//使用 AnnotationConfiguration 建立会话工厂private static Configuration configuration = new AnnotationConfiguration(); private static org.hibernate.SessionFactory sessionFactory;private static String configFile = CONFIG_FILE_LOCATION;static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); }}private HibernateSessionFactory() {}/** * 获得session */public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session;}/** * 重新获得session * */public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); }}/** * 关闭session * * @throws HibernateException */public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); }}/** * 获得sessionfactory * */public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory;}/** * 设置配置文件 */public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null;}/** * 获得Configuration * */public static Configuration getConfiguration() { return configuration;}
}
好了,这样就不必每次都写一堆繁琐重复的代码了。
- Hibernate 通用操作类 BaseHibernateDao
- HIbernate------> BaseHibernateDAO类
- Hibernate通用数据库操作代码
- Hibernate通用数据库操作代码
- Hibernate封装通用数据操作基类DAO
- Hibernate封装通用数据操作基类DAO
- hibernate通用分页类
- hibernate通用的类
- Hibernate编写通用数据库操作代码
- Hibernate编写通用数据库操作代码
- Hibernate编写通用数据库操作代码
- 使用Hibernate编写通用数据库操作代码
- Hibernate编写通用数据库操作代码
- Hibernate编写通用数据库操作代码
- Hibernate编写通用数据库操作代码演示
- 使用Hibernate编写通用数据库操作代码
- BaseHibernateDAO.java
- JDBC通用操作类
- [latex] 格式控制
- LeetCode 题解(171): Jump Game
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(所有根到叶子结点组组成的数字相加)】
- 【LeetCode-面试算法经典-Java实现】【130-Surrounded Regions(环绕区域)】
- 【LeetCode-面试算法经典-Java实现】【134-Gas Station(加油站问题)】
- Hibernate 通用操作类 BaseHibernateDao
- C语言的指针
- 在MFC中添加多个音乐
- 集合的遍历
- Node.js开发入门—使用AngularJS内置服务
- 在Android上使用Google V8 JS 引擎
- C++内存管理详解
- 开发相关琐碎记录
- 转自 TechTarget博客:漫谈Scale-out和Scale-up