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

时间:2021-05-19

复制代码 代码如下:
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;
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章