亲宝软件园·资讯

展开

链接数据库 java自定义动态链接数据库示例

人气:0
想了解java自定义动态链接数据库示例的相关内容吗,在本文为您仔细讲解链接数据库的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:自定义,链接数据库,下面大家一起来学习吧。

复制代码 代码如下:

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; 
    } 
}

加载全部内容

相关教程
猜你喜欢
用户评论