package com.vci.server.base.persistence.dao;
|
|
import java.io.File;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.URL;
|
import java.sql.Connection;
|
import java.sql.DatabaseMetaData;
|
import java.sql.SQLException;
|
import java.util.Enumeration;
|
import java.util.List;
|
import java.util.ArrayList;
|
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<VciSession> threadLocal = new ThreadLocal<VciSession>();
|
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);
|
|
//loadHbmFiles();
|
|
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 <code>SessionFactory</code> 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);
|
|
loadHbmFiles();
|
|
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() {
|
ServerWithLog4j.logger.info("加载Hibernate对象映射");
|
try {
|
List<InputStream> iss = loadResources(MAP_FILE_RESOURCE, HibernateSessionFactory.class.getClassLoader());
|
//InputStream is = HibernateSessionFactory.class.getResourceAsStream(MAP_FILE_RESOURCE);
|
//if (is != null)
|
for (InputStream is : iss)
|
{
|
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);
|
} catch (IOException e) {
|
// TODO Auto-generated catch block
|
e.printStackTrace();
|
}
|
}
|
|
private static List<InputStream> loadResources(final String name, final ClassLoader classLoader) throws IOException {
|
final List<InputStream> list = new ArrayList<InputStream>();
|
final Enumeration<URL> systemResources =
|
(classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader)
|
.getResources(name);
|
while (systemResources.hasMoreElements()) {
|
list.add(systemResources.nextElement().openStream());
|
}
|
return list;
|
}
|
}
|