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;
}
}
相关文章
Java使用poi-tl1.9.1生成Word文档的技巧分享
本文将简单介绍poi-tl的相关知识,通过一个实际的案例实践,充分介绍如何利用poi-tl进行目标文档的生成,同时分享几个不同的office版本如何进行图表生成的解决方案,需要的朋友可以参考下2023-09-09Spring Boot如何配置yml配置文件定义集合、数组和Map
这篇文章主要介绍了Spring Boot 优雅配置yml配置文件定义集合、数组和Map,包括Spring Boot yml配置文件定义基本数据类型和引用数据类型的方式,需要的朋友可以参考下2023-10-10java jdk1.8 使用stream流进行list 分组归类操作
这篇文章主要介绍了java jdk1.8 使用stream流进行list 分组归类操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-10-10
最新评论