创建HibernateSessionFactory代码如下:
package com.hibernate;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
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.
* NOTICE: Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file. That
* is place the config file in a Java package - the default location
* is the default Java package.<br><br>
* Defaults: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml"</code>
* You can change location with setConfigFile method
* session will be rebuilded after change of config file
*/
private static String CONFIG_FILE_LOCATION = "/com/hibernate/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getCurrentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
try {
if (session == null || !session.isOpen()|| session.connection().isClosed()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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 closeCurrentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static 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;
}
}
在某个类中使用,则应要:
// 开启session
public void openSession() {
this.session = HibernateSessionFactory.getCurrentSession();
}
// 关闭session
public void closeSession() throws HibernateException {
this.session.close();
}
或者
// 开启事务
public void beginTransaction() throws HibernateException {
try {
this.session = HibernateSessionFactory.getCurrentSession();
this.transaction = this.session.beginTransaction();
} catch (Exception ex) {
throw new HibernateException("开启事务时发生如下错误:" + ex.getMessage());
}
}
// 提交事务
public void commitTransaction() throws HibernateException {
try {
this.transaction.commit();
} catch (Exception ex) {
ex.printStackTrace();
this.transaction.rollback();
System.out.println("提交事务时发生如下错误:" + ex.getMessage());
throw new HibernateException("提交事务时发生如下错误:" + ex.getMessage());
} finally {
this.session.close();
}
}
分享到:
相关推荐
HibernateSessionFactory.java
在`HibernateSessionFactory.java`这个文件中,我们可能看到对上述过程的封装,例如创建`SessionFactory`的静态方法,以及提供会话的获取和关闭功能。这样的封装有助于代码的整洁和复用。 在实际应用中,`...
标题提到的"新Hibernate SessionFactory().getCurrentSession()猫腻"揭示了一个常见的使用误区或者说是陷阱,即不正确地使用SessionFactory的getCurrentSession()方法。这篇文章可能探讨了这个方法在实际应用中的...
Session s= HibernateSessionFactory.getSession(); 就是Hibernate的工具java类
本篇文章将深入探讨`HibernateSessionFactory`及其在Hibernate中的作用,以及如何使用它来实现增、删、查、改(CRUD)操作。 `SessionFactory`是Hibernate的核心组件,它是线程安全的,负责管理数据库连接和会话。`...
修改了Hibernate的源码,可动态增加映射文件
Session session = HibernateSessionFactory.getSession(); Transaction tx = session.beginTransaction(); session.save(user); // 保存用户 tx.commit(); HibernateSessionFactory.closeSession(); } ``` ...
本文将详细讲解如何在Spring 3.2.3版本中配置SessionFactory,以便整合Hibernate 4.2.2,实现对数据库操作的高效管理。SessionFactory是Hibernate的核心组件,它负责创建Session对象,而Session则是与数据库交互的...
Session session = HibernateSessionFactory.currentSession(); Transaction t = session.beginTransaction(); session.save(o); t.commit(); HibernateSessionFactory.clossSession(); } ``` 2. 删除数据...
首先,`HibernateSessionFactory`是Hibernate的核心组件之一,它负责创建`Session`对象。`Session`对象是与数据库进行交互的接口,类似于JDBC中的Connection。`HibernateSessionFactory`通常在应用启动时初始化一次...
如果选择自定义配置文件的位置或名称,则需要通过`HibernateSessionFactory`类中的`CONFIG_FILE_LOCATION`属性来指定实际的配置文件路径。 **配置文件中的主要内容包括:** - **数据库连接信息**:包括数据库的URL...
Session session = HibernateSessionFactory.getSession(); News news = new News(); news.setContent("my content"); news.setTitle("my title"); news.setDate("my date"); Transaction trans = session.begin...
Session session = HibernateSessionFactory.currentSession(); Transaction t = session.beginTransaction(); session.save(o); t.commit(); HibernateSessionFactory.closeSession(); } ``` 这里的关键步骤...
`HibernateSessionFactory` 类是Hibernate应用中常见的一个工具类,用于管理和提供与当前线程相关的Session实例。让我们详细了解一下`HibernateSessionFactory`类中的关键方法和其背后的原理。 1. **配置和初始化...
- 获取Session对象:通过`HibernateSessionFactory.getSession()`方法获取一个`Session`实例。 - 开始事务:调用`session.beginTransaction()`开始一个事务。 - 创建查询:使用`session.createQuery`创建HQL查询语句...
本文将详细讲解Hibernate工具,包括`hibernate.cfg.xml`配置文件和`HibernateSessionFactory.java`类在Hibernate中的重要角色。 **1. hibernate.cfg.xml配置文件** `hibernate.cfg.xml`是Hibernate应用的基础配置...