田源
2024-03-07 4b4083fd73dc27ece42f4835483565eef0e4f608
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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;
    }
}