package com.vci.server.base.persistence.dao; import java.io.File; import java.io.InputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.impl.SessionImpl; import org.hibernate.jdbc.JDBCContext; import com.vci.common.log.ServerWithLog4j; import com.vci.corba.common.data.VCIInvocationInfo; /** * 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 }. * @author Administrator * */ 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 final Log log = LogFactory.getLog(HibernateSessionFactory.class); private static String CONFIG_FILE_LOCATION="properties/hibernate.cfg.xml"; private static String MAP_FILE_RESOURCE="/properties/hibernate.map.xml"; //private static String MAP_FILE_RESOURCE="hibernate.map.xml"; private static final ThreadLocal threadLocal = new ThreadLocal(); private static Configuration configuration = new Configuration(); private static SessionFactory sessionFactory; private static DbType _dbType = DbType.Unknow; static { try { ServerWithLog4j.logger.info("Init Hibernate"); File file = new File(CONFIG_FILE_LOCATION); configuration.configure(file); ServerWithLog4j.logger.info("加载Hibernate对象映射:Begin"); loadHbmFiles(); ServerWithLog4j.logger.info("加载Hibernate对象映射:End"); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { ServerWithLog4j.logger.error("Error Creating SessionFactory", e); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Return the ThreadLocal session instance. Lazy initialize * the SessionFactory if needed. * @return * @throws HibernateException */ public static synchronized Session getSession() throws HibernateException { VciSession vciSession = (VciSession) threadLocal.get(); if (vciSession == null) { vciSession = new VciSession(); } if (vciSession.getSession() == null || !vciSession.getSession().isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } Session session = (sessionFactory != null) ? sessionFactory.openSession() : null; vciSession.setSession(session); threadLocal.set(vciSession); ServerWithLog4j.logger.debug("--> Open Session"); } return vciSession.getSession(); } public static void setVciSessionInfo(VCIInvocationInfo info) { VciSession vciSession = (VciSession) threadLocal.get(); if (vciSession == null) { vciSession = new VciSession(); threadLocal.set(vciSession); } vciSession.setVciInfo(info); } public static VCIInvocationInfo getVciSessionInfo() { VciSession vciSession = (VciSession) threadLocal.get(); if (vciSession == null) { return null; } VCIInvocationInfo vii = vciSession.getVciInfo(); if (vii == null) { vii = new VCIInvocationInfo(); } return vii; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { File file = new File(CONFIG_FILE_LOCATION); configuration.configure(file); ServerWithLog4j.logger.info("加载Hibernate对象映射:Begin"); loadHbmFiles(); ServerWithLog4j.logger.info("加载Hibernate对象映射:End"); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { ServerWithLog4j.logger.error("Error Rebuild SessionFactory", e); e.printStackTrace(); } } /** * Close the single hibernate session instance. * @throws HibernateException */ public static void closeSession() throws HibernateException { VciSession vcisession = (VciSession) threadLocal.get(); threadLocal.set(null); Session session = vcisession.getSession(); if (session != null ) { session.close(); session = null; ServerWithLog4j.logger.debug("<--Close Session"); } } /** * fetch session factory * * @return */ public static SessionFactory getSessionFactory() { return sessionFactory; } /** * session factory will be rebuiled in the next call * @param configFile */ public static void setConfigFile(String configFile) { HibernateSessionFactory.CONFIG_FILE_LOCATION = configFile; sessionFactory = null; } /** * session factory will be rebuiled in the next call * @param configFile */ public static void setHbmFiles(String[] files) { //_hbmFiles = files; sessionFactory = null; } /** * fetch hibernate configuration. * @return */ public static Configuration getConfiguration() { return configuration; } /** * 返回绑定到当前线程上下文中的Connection对象 * @return 绑定到当前线程上下文中的Connection对象 */ public static java.sql.Connection getSessionConnection(){ Session session = HibernateSessionFactory.getSession(); SessionImpl sessionImpl = (SessionImpl)session; JDBCContext jdbcContext = sessionImpl.getJDBCContext(); Connection connection = jdbcContext.getConnectionManager().getConnection(); return connection; } public static DbType getDbType() { if (_dbType != DbType.Unknow) return _dbType; Connection con = getSessionConnection(); try { DatabaseMetaData dbmd = con.getMetaData(); String driveName = dbmd.getDriverName(); String productName = dbmd.getDatabaseProductName(); //System.out.println("===============DBTYPE=============="); //System.out.println("\tdriveName=" + driveName + "; productName=" + productName); ServerWithLog4j.logger.info("DB driveName=" + driveName + "; DB ProductName=" + productName); //System.out.println("===============DBTYPE=============="); if (productName.equalsIgnoreCase("Oracle")) // Oracle 数据库 _dbType = DbType.ORACL; else if (driveName.equalsIgnoreCase("Dm dbms")) // 达梦数据库 _dbType = DbType.DM8; else _dbType = DbType.Unknow; // 数据库未知 } catch (SQLException e) { e.printStackTrace(); _dbType = DbType.Unknow; } return _dbType; } private static void loadHbmFiles() { try { //List iss = loadResources(MAP_FILE_RESOURCE, HibernateSessionFactory.class.getClassLoader()); //List iss = loadResources(MAP_FILE_RESOURCE, null); InputStream is = HibernateSessionFactory.class.getResourceAsStream(MAP_FILE_RESOURCE); //for (InputStream is : iss) if (is != null) { SAXReader reader = new SAXReader(); Document doc; doc = reader.read(is); Element root = doc.getRootElement(); List lst = root.elements("mapping"); for (Object el : lst) { Attribute at = ((Element)el).attribute("resource"); if (at != null) { String hbmFile = at.getValue(); configuration.addResource(hbmFile); } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); ServerWithLog4j.logger.error("加载对象映射失败", e); } } // private static List loadResources(final String name, final ClassLoader classLoader) throws IOException { // final List list = new ArrayList(); // final Enumeration systemResources = // (classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader) // .getResources(name); // while (systemResources.hasMoreElements()) { // ServerWithLog4j.logger.info(MAP_FILE_RESOURCE + ":" + systemResources.nextElement().getPath()); // // list.add(systemResources.nextElement().openStream()); // } // return list; // } }