解析下HibernateSessionFactory.java


轉自  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 或 timestamp
								map.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 或 timestamp
									map.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;
	}
}


發佈了19 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章