ludc
2025-01-16 986aa62ed00bee39363bab41b4eeb8259d446efd
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
package com.vci.server.query.util;
 
import java.sql.Connection;
 
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;
 
public class HibernateSessionUtil {
    
    private static ThreadLocal<Session> session = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory;
 
    static{
        try{
            sessionFactory = new Configuration().configure("properties/hibernate.cfg.xml").buildSessionFactory();
        }catch (Throwable e){
            e.printStackTrace();
            ServerWithLog4j.logger.error("Initial SessionFactory fail...", e);
        }
    }
            
    
    public static Session getSession(){
        Session s = session.get();
        if(s == null){
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }
    
    public static void closeSession(){
        Session s = session.get();
        if(s != null){
            s.close();
            session.set(null);
        }
    }
    
    public static Connection getConnection(){
        SessionImpl sessionImpl = (SessionImpl)getSession();
        JDBCContext jdbcContext = sessionImpl.getJDBCContext();
        return jdbcContext.getConnectionManager().getConnection();
    }
}