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;
}
}
分享到:
相关推荐
《深入理解HibernateUtil:高效管理Hibernate Session与SessionFactory》 Hibernate,作为Java领域广泛使用的对象关系映射(ORM)框架,极大地简化了数据库操作。而HibernateUtil则是为了方便开发者管理Hibernate的...
标题"HibernateUtil分装完整版HQL查询"暗示了这是一个关于使用HibernateUtil工具类来封装和执行HQL(Hibernate Query Language)查询的教程或代码示例。描述中的重复信息进一步强调了这个主题,意味着我们将探讨如何...
HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装
【标题】:Hibernate入门实例——基于HibernateUtil的数据库操作封装 在Java开发中,Hibernate作为一个强大的对象关系映射(ORM)框架,极大地简化了数据库操作。本实例将深入浅出地介绍如何使用Hibernate进行基本...
HibernateUtil工具类
本教程聚焦于“完善HibernateUtil类及HQL查询入门”,让我们深入探讨这两个关键概念。 首先,`HibernateUtil` 类是 Hibernate 教程中常见的一种工具类,它的主要作用是提供对 Hibernate 框架的简单封装,以方便进行...
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
Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Class class1 = new Class(); // set class1 properties List<Student> students =...
`HibernateUtil`工具类就是对Hibernate框架功能的一种封装,简化了对数据库的操作。 在`HibernateUtil`工具类中,常见的方法有以下几类: 1. **初始化SessionFactory**: SessionFactory是Hibernate的核心组件,它...
} <br> public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...
return HibernateUtil.getSession().createCriteria(clazz).list(); } @SuppressWarnings("unchecked") public List<T> findList(int pageNo, int pageSize) { return HibernateUtil.getSession()....
在IT行业中,数据库操作是应用程序开发中的重要环节,而Hibernate作为一种强大的对象关系映射(ORM)框架,极大地简化了Java开发者对数据库的操作。本篇将详细介绍一个基于Hibernate封装的增删改查工具类,该工具类...
Session session = HibernateUtil.currentSession(); // 获取当前会话 Transaction tx = null; // 事务 Users po = new Users(); // 实体对象 po = transCommerceInfoVOtoPO(vo, po); // 将 VO 转换为 PO try...
- **编写 HibernateUtil 工具类**:用于获取SessionFactory和Session,简化操作。 - **编写数据访问层**:使用HibernateUtil,实现CRUD(创建、读取、更新、删除)操作。 2. **Domain Object 规范** - **无参...
- 模型层:在HibernateUtil中增加了公告新增的业务逻辑方法,接收封装用户输入的实体对象。 4. **公告删除** - 界面层:删除操作在公告列表页面中进行,无单独的删除界面。若用户无权限,会显示bbc_nomodify.jsp...
控制层的`updateShen.jsp`逻辑页面接收用户输入,调用`HibernateUtil`中的`updateshenhe()`方法进行更新操作,并根据执行结果决定页面跳转。 3. **申请的审核**:未提供详细设计,通常涉及用户提交审批申请的功能。...