程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> java自定義動態鏈接數據庫示例

java自定義動態鏈接數據庫示例

編輯:JAVA編程入門知識

代碼如下:

package dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * @author minxuenetcn
 */
public class HibernateSessionFactory { 

    private final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 
    private Configuration configuration = new Configuration();  
    private org.hibernate.SessionFactory sessionFactory; 

    /**
     * hibernate.cfg.xml
     * @param configFile
     */
    public void setConfiguration(String configFile){
     this.configuration=new Configuration();
     configuration.configure(configFile);

    } 
    /**
     * Returns the ThreadLocal Session instance.
     *  @return Session
     *  @throws HibernateException
     */ 
    public 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 void rebuildSessionFactory() {   

     try { 
            sessionFactory = this.configuration.buildSessionFactory(); 
        } catch (Exception e) { 
            System.err 
                    .println("%%%% Error Creating SessionFactory %%%%"); 
            e.printStackTrace(); 
        } 
    } 

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */ 
    public void closeSession() throws HibernateException { 
        Session session = (Session) threadLocal.get(); 
        threadLocal.set(null); 
        if (session != null) { 
            session.close(); 
        } 
    } 
    /**
     *  return session factory
     *
     */ 
    public org.hibernate.SessionFactory getSessionFactory() { 
        return sessionFactory; 
    } 
    /**
     *  return hibernate configuration
     */ 
    public Configuration getConfiguration() { 
        return configuration; 
    } 
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved