HibernateUtil往往是用来生成SessionFactory以及getSession与closeSession的,主要是几个静态方法。
一、使用ThreadLocal隔离执行所使用的数据,避开Session多线程之间数据共享问题,主要是几个静态方法:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final Log log=LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static
{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Throwable ex)
{
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal thread_var=new ThreadLocal();
public static Session currentSession()
{
Session s=(Session)thread_var.get();
if(s==null)
{
s=sessionFactory.openSession();
thread_var.set(s);
}
return s;
}
public static void closeSession()
{
Session s=(Session)thread_var.get();
if(s!=null)
s.close();
thread_var.set(null);
}
}
二、不使用ThreadLocal的:
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Exception building SessionFactory: "
+ ex.getMessage(), ex);
}
}
public static Session currentSession() throws HibernateException {
Session s = sessionFactory.openSession();
return s;
}
public static void closeSession(Session s) {
s.close();
}
}
三、用MyEclipse自动生成的HibernateUtil:
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static 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 static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
分享到:
相关推荐
管理hibernate的session sessionFactiory的实现类
HibernateUtil分装完整版HQL查询HibernateUtil分装完整版HQL查询
HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装
HibernateUtil工具类
hibernate入门实例封装了HibernateUtil,完成数据库的添加操作,和查询操作。 Session的save方法和get方法。
06_传智播客hibernate教程_完善HibernateUtil类及hql查询入门
Hibernate5.2.1 的工具类 创建session 和 sessionFactory
欢迎大家咨询,我会尽量去与大家讲解,希望对你们有所帮助
HibernateUtil.java HibernateUtils.java HttpRequester.java HttpRespons.java HttpUtil.java MD5Util.java Pagination.java PropertiesUtil.java RegUtil.java StringUtil.java UploadUtil.java UUIDUtils.java
} <br> public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...
hibernate 一对多测试工程,博客介绍请参照: http://blog.csdn.net/smilefyx/article/details/48596665
return HibernateUtil.getSession().createCriteria(clazz).list(); } @SuppressWarnings("unchecked") public List<T> findList(int pageNo, int pageSize) { return HibernateUtil.getSession()....
一个工具类实现了增删改查 util comm.util beanutils 方便了获取session和sessionFactory
自己编写的HibernateUtil类,比较全面,方法均通过测试
SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Serializable id = null; Transaction tran = null; try{ tran = session.beginTransaction(); ...
HibernateUtil工具类,封装了Hibernate的事务,增,删,改,查,以及分页的方法!
2、采用Jsp->Action->Service->Dao的编码方式,封装了HibernateUtil、SpringUtil、HqlUtil等工具,以及简化了增删查改操作。 3、此底层包含泛型DAO、Proxool连接池、国际化语言、DateUtil工具、ExcelUtil报表工具、...
Hibernate4_Inheritance_Annotation 该程序演示了如何使用 Annotations 在 Hibernate 中使用继承。... 每个层次类的一个表 - 打开 HibernateUtil.java 并启用每个层次类的一个表并运行 Application2.ja