解析下HibernateSessionFactory.java

来源:互联网 发布:怎么在淘宝注册店铺 编辑:程序博客网 时间:2024/06/07 01:42


转自  http://bbs.csdn.net/topics/350268371


package org.xmh.db;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution.  Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */public class HibernateSessionFactory {    /**      * Location of hibernate.cfg.xml file.     * Location should be on the classpath as Hibernate uses       * #resourceAsStream style lookup for its configuration file.      * The default classpath location of the hibernate config file is      * in the default package. Use #setConfigFile() to update      * the location of the configuration file for the current session.        */    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();    private  static Configuration configuration = new Configuration();    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() {    }/**     * Returns the ThreadLocal Session instance.  Lazy initialize     * the <code>SessionFactory</code> if needed.     *     *  @return Session     *  @throws HibernateException     */    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;    }/**     *  Rebuild hibernate session factory     *     */public static void rebuildSessionFactory() {try {configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();}}/**     *  Close the single hibernate session instance.     *     *  @throws HibernateException     */    public static void closeSession() throws HibernateException {        Session session = (Session) threadLocal.get();        threadLocal.set(null);        if (session != null) {            session.close();        }    }/**     *  return session factory     *     */public static org.hibernate.SessionFactory getSessionFactory() {return sessionFactory;}/**     *  return session factory     *     *session factory will be rebuilded in the next call     */public static void setConfigFile(String configFile) {HibernateSessionFactory.configFile = configFile;sessionFactory = null;}/**     *  return hibernate configuration     *     */public static Configuration getConfiguration() {return configuration;}}


HiberbateSessionFactory.java 有如下5个功能:

1 创建Configuration对象
2 加载hibernate.cfg.xml文件
3 创建sessionFactory对象
4 得到Session
5 关闭Session


一般情况DAO层的类继承一个BaseDAO类,在BaseDAO.java文件使用HibernateSessionFactory.java文件的功能,BaseDAO.java如下

package *.*.*.dao;import java.io.Serializable;import java.sql.Connection;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import java.sql.Timestamp;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Vector;import org.apache.log4j.Logger;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import org.xmh.db.HibernateSessionFactory;public class BaseDAO {private final static Logger logger = Logger.getLogger(BaseDao.class);public void save(final Object entity) {Session sn = null;try {sn = HibernateSessionFactory.getSession();Transaction ts = sn.beginTransaction();sn.save(entity);ts.commit();} catch (Exception ex) {logger.error("save() error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}}public void update(final Object entity) {Session sn = null;try {sn = HibernateSessionFactory.getSession();Transaction ts = sn.beginTransaction();sn.update(entity);ts.commit();} catch (Exception ex) {logger.error("update() error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}}public void delete(final Object entity) {Session sn = null;try {sn = HibernateSessionFactory.getSession();Transaction ts = sn.beginTransaction();sn.delete(entity);ts.commit();} catch (Exception ex) {logger.error("delete() error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}}public Object get(final Class entity, final Serializable id) {Session sn = null;Object obj = null;try {sn = HibernateSessionFactory.getSession();obj = sn.get(entity, id);} catch (Exception ex) {logger.error("get() error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}return obj;}public List findAll(final Class entity) {Session sn = null;List list = null;try {sn = HibernateSessionFactory.getSession();// Transaction ts = sn.beginTransaction();list = sn.createQuery(" from " + entity.getName()).list();// ts.commit();} catch (Exception ex) {logger.error("find() error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}return list;}public List find(final String query) {Session sn = null;List list = null;try {sn = HibernateSessionFactory.getSession();// Transaction ts = sn.beginTransaction();list = sn.createQuery(query).list();// ts.commit();} catch (Exception ex) {logger.error("find() error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}return list;}        public List findBySql(final String sql) {        Session sn = null;        List list = null;        try {            sn = HibernateSessionFactory.getSession();            // Transaction ts = sn.beginTransaction();            list = sn.createSQLQuery(sql).list();            // ts.commit();        } catch (Exception ex) {            logger.error("find() error:" + ex.getMessage(), ex);        } finally {            HibernateSessionFactory.closeSession();        }        return list;    }public List find(final String queryStr, final Object[] parameter) {Session sn = null;List list = null;try {sn = HibernateSessionFactory.getSession();// Transaction ts = sn.beginTransaction();Query query = sn.createQuery(queryStr);int len = parameter.length;for (int i = 0; i < len; i++) {query.setParameter(i, parameter[i]);}list = query.list();// ts.commit();} catch (Exception ex) {logger.error("find error:" + ex.getMessage(), ex);} finally {HibernateSessionFactory.closeSession();}return list;}/** * 得到分页的结果 *  * @param currentPage : *            当前页 * @param pageSize : *            每页要显示多少条数据 * @param countSql : *            统计Hql * @param countValues : *            统计Hql中的值(是一个对象数组) * @param sql * @param values * @return */public HashMap getPageResult(int currentPage, final int pageSize,final String countHql, final Object[] countValues,final String hql, final Object[] values) {HashMap map = new HashMap();List list = new ArrayList();int totalSize = getTotalSize(countHql, countValues);int start = 0; // 第currentPage页数据是从哪条记录开始的int end = 0; // 第currentPage页数据是从哪条记录结束的int totalPage = 0;/** * *** 找出当前要显示页(currentpage)的开始记录号"start"和结束记录号"end",以便只把当前页的数据给找出来 * ***** */totalPage = (int) Math.ceil((double) totalSize / pageSize); // 共有多少页// System.out.println("total:"+total+" totalPage:"+totalPage+"// currentPage:"+currentPage);// 如果当前页大于总页数,则显示最后一页if (currentPage > totalPage)currentPage = totalPage;// 如果当前页小于0,则显示第一页if (currentPage < 1)currentPage = 1;// 根据条件判断,取出所需记录start = pageSize * (currentPage - 1);end = start + pageSize;if (end > totalSize)end = totalSize; // 因为在下面的循环中用到的是小于,所以在此用"="list = getCurrentPageResult(start, pageSize, hql, values);map.put("list", list);map.put("currentPage", String.valueOf(currentPage));map.put("totalPage", String.valueOf(totalPage));map.put("pageSize", String.valueOf(pageSize));map.put("totalSize", String.valueOf(totalSize));return map;}private int getTotalSize(String countHql, Object[] countValues) {Session session = HibernateSessionFactory.getSession();Query query = session.createQuery(countHql);if (countValues != null) {for (int i = 0; i < countValues.length; i++) {String type = getType(countValues[i].getClass().getName());if (type.equals("String")) {query.setString(i, "%" + countValues[i].toString() + "%");} else if (type.equals("Date")) {query.setDate(i, (Date) countValues[i]);} else if (type.equals("Integer")) {query.setInteger(i, ((Integer) countValues[i]).intValue());} else if (type.equals("Boolean")) {query.setBoolean(i, ((Boolean) countValues[i]).booleanValue());}}}return ((Integer) query.uniqueResult()).intValue();}/** * 功能:得到分页的结果(当前页) *  * @param start : *            开始记录号 * @param pageSize : *            每页显示多少条记录 * @param sql : *            要查询的sql语句 * @param values : *            sql语句中的变量值 * @return */public List getCurrentPageResult(final int start, final int pageSize,final String sql, final Object[] values) {Session session = HibernateSessionFactory.getSession();Query query = session.createQuery(sql);if (values != null) {for (int i = 0; i < values.length; i++) {String type = getType(values[i].getClass().getName());if (type.equals("String")) {query.setString(i, "%" + values[i].toString() + "%");} else if (type.equals("Date")) {query.setDate(i, (Date) values[i]);} else if (type.equals("Integer")) {query.setInteger(i, ((Integer) values[i]).intValue());} else if (type.equals("Boolean")) {query.setBoolean(i, ((Boolean) values[i]).booleanValue());}}}query.setFetchSize(30);query.setFirstResult(start);query.setMaxResults(pageSize);return query.list();}private String getType(String typeParam) {int last = typeParam.lastIndexOf(".");return typeParam.substring(last + 1);}/** * 执行sql语句 *  * @param sql * @return List HashMap * @throws YiChaAdException */public List executeQuery(String sql) {Session sn = null;ResultSet rs = null;List list = null;try {sn = HibernateSessionFactory.getSession();Connection conn = sn.connection();rs = conn.createStatement().executeQuery(sql);list = getList(rs);} catch (Exception e) {logger.error("executeQuery :" + e.getMessage(), e);} finally {HibernateSessionFactory.closeSession();}return list;}/** * 执行sql语句 *  * @param sql * @return List HashMap * @throws YiChaAdException */public int executeUpdate(String sql) {Session sn = null;ResultSet rs = null;int n = 0;try {sn = HibernateSessionFactory.getSession();Connection conn = sn.connection();n = conn.createStatement().executeUpdate(sql);conn.commit();conn.close();} catch (Exception e) {logger.error("executeQuery :" + e.getMessage(), e);} finally {HibernateSessionFactory.closeSession();}return n;}/** * 执行sql语句 *  * @param sql * @return List HashMap * @throws YiChaAdException */public boolean execute(String sql) {Session sn = null;ResultSet rs = null;boolean mark = false;try {sn = HibernateSessionFactory.getSession();Connection conn = sn.connection();mark = conn.createStatement().execute(sql);conn.commit();conn.close();} catch (Exception e) {logger.error("executeQuery :" + e.getMessage(), e);} finally {HibernateSessionFactory.closeSession();}return mark;}/* * @由rs得到ArrayList */ArrayList getList(ResultSet rs) {ArrayList vector = new ArrayList();ResultSetMetaData rsmd = null;HashMap map = new HashMap();int columnCount = 0;try {rsmd = rs.getMetaData();columnCount = rsmd.getColumnCount();String[] columnName = new String[columnCount];for (int i = 0; i < columnCount; i++) {columnName[i] = rsmd.getColumnName(i + 1);}while (rs.next()) {map = new HashMap();// System.out.println("rows:"+rs.getRow()+"// id:"+rs.getInt("id")+" email:"+rs.getString("email"));for (int i = 0; i < columnCount; i++) {int type = rsmd.getColumnType(i + 1);// System.out.println(columnName[i]+type);try {if (rs.getObject(i + 1) == null)map.put(columnName[i].toLowerCase(), null);else {switch (type) {case 4: // integer型map.put(columnName[i], Integer.valueOf(rs.getString(i + 1)));break;case 91: // date型map.put(columnName[i], rs.getDate(i + 1));break;case 93: // datetime 或 timestampmap.put(columnName[i], (Timestamp) rs.getObject(i + 1));break;case -7: // boolean型map.put(columnName[i], (Boolean) rs.getObject(i + 1));break;default:map.put(columnName[i], rs.getString(i + 1));}}} catch (Exception e) {map.put(columnName[i], "");// System.out.println("列名:"+columnName[i]+"出错!"+e.getMessage().toString());}}vector.add(map);}} catch (SQLException e) {logger.error("getList()方法出错:", e);}return vector;}/*********  以下部分是SQL(不是HQL)的分页实现部分 *************//** * 功能:得到指定页的数据 *  @param:countSql:查询统计(只要count(*)和where条件)   *  @param:sql:查询数据 *  @param:currentPage:当前是第几页 *  @param:pageSize:每页显示多少条记录 *  @return  *   HashMap: *    "totalPage":共有多少页 *  "currentPage":当前是第几页 *  "list":得到的数据列表(Vector类型) */public HashMap getPageResult_sql(String countSql,String sql ,int currentPage,int pageSize) {Session sn = null;Statement stmt = null;ResultSet rs = null;sn = HibernateSessionFactory.getSession();Connection conn = sn.connection();int total= 0;  //总共有多少条记录int totalPage = 0;//共有多少页try{stmt = conn.createStatement();rs = stmt.executeQuery(countSql);if (rs.next()) total = rs.getInt(1); }catch(SQLException e){logger.error("执行分页getPageResultSet()在得到总页数时出错:"+countSql,e);}// 设置当前页数和总页数 totalPage = (int)Math.ceil((double)total/pageSize);   //共有多少页 if(currentPage<1) currentPage=1;//如果当前页大于总页数,则显示最后一页if(currentPage>totalPage) currentPage = totalPage;//如果当前页小于0,则显示第一页if(currentPage<1) currentPage = 1;// 根据条件判断,取出所需记录int start = pageSize*(currentPage-1);sql = sql + " LIMIT " + start + " , " + pageSize; Vector vector = getResultSet_sql(sql);  HashMap hashMap = new HashMap();hashMap.put("totalPage",Integer.valueOf(totalPage));   //共有多少页hashMap.put("currentPage",Integer.valueOf(currentPage));hashMap.put("list",vector);return hashMap;}private Vector getResultSet_sql(String sql) {Session sn = null;Statement stmt = null;ResultSet rs = null;sn = HibernateSessionFactory.getSession();Connection conn = sn.connection();Vector vector = null;try{stmt = conn.createStatement();rs = stmt.executeQuery(sql);vector = getVector_sql(rs);}catch(SQLException e){logger.error("执行SQL出错:"+sql,e);}finally{HibernateSessionFactory.closeSession();}return vector;}/* * @由rs得到Vector */private Vector getVector_sql(ResultSet rs) {Vector vector = new Vector();ResultSetMetaData rsmd = null;HashMap map = new HashMap();int columnCount = 0;try{rsmd = rs.getMetaData();columnCount = rsmd.getColumnCount();String[] columnName = new String[columnCount];for(int i=0;i<columnCount;i++){columnName[i]=rsmd.getColumnName(i+1);}while(rs.next()){map = new HashMap();//System.out.println("rows:"+rs.getRow()+" id:"+rs.getInt("id")+"  email:"+rs.getString("email"));for(int i=0;i<columnCount;i++){int type = rsmd.getColumnType(i + 1);//System.out.println(columnName[i]+type);try{if(rs.getObject(i+1)==null)map.put(columnName[i],null);else{switch (type) {case 4://integer型map.put(columnName[i], Integer.valueOf(rs.getInt(i+1)) );break;case 91://date型map.put(columnName[i],rs.getDate(i+1));break;case 93://datetime 或 timestampmap.put(columnName[i],(Timestamp)rs.getObject(i+1));break;case -7://boolean型map.put(columnName[i],(Boolean)rs.getObject(i+1));break;case 3: //BigDecimal型    map.put(columnName[i],rs.getBigDecimal(i+1));    break;default:map.put(columnName[i],rs.getString(i+1));}}}catch(Exception e){map.put(columnName[i],"");//System.out.println("列名:"+columnName[i]+"出错!"+e.getMessage().toString());}}vector.add(map);}}catch(SQLException e){logger.error("getVector()方法出错:",e);}return vector;}}


0 0
原创粉丝点击