`
maybe723
  • 浏览: 45813 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论

HibernateUtil

阅读更多
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;



public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure("/hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Throwable ex) {
            ex.printStackTrace();
            System.out.println("Initial SessionFactory creation failed.");
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal tLocalsess = new ThreadLocal();

    public static final ThreadLocal tLocaltx = new ThreadLocal();

    /*
     * getting the thread-safe session for using
     */
    public static Session currentSession() {
        Session session = (Session) tLocalsess.get();

        //open a new one, if none can be found.
        try {
            if (session == null || !session.isOpen()) {
                session = openSession();
                tLocalsess.set(session);
            }
        } catch (HibernateException e) {
            //throw new HibernateException(e);
            e.printStackTrace();
        }
        return session;
    }

    /*
     * closing the thread-safe session
     */
    public static void closeSession() {

        Session session = (Session) tLocalsess.get();
        tLocalsess.set(null);
        try {
            if (session != null && session.isOpen()) {
                session.close();
            }

        } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    /*
     * begin the transaction
     */
    public static void beginTransaction() {
        System.out.println("begin tx");
        Transaction tx = (Transaction) tLocaltx.get();
        try {
            if (tx == null) {
                tx = currentSession().beginTransaction();
                tLocaltx.set(tx);
            }
        } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    /*
     * close the transaction
     */
    public static void commitTransaction() {
        Transaction tx = (Transaction) tLocaltx.get();
        try {
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
                tx.commit();
            tLocaltx.set(null);
             } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    /*
     * for rollbacking
     */
    public static void rollbackTransaction() {
        Transaction tx = (Transaction) tLocaltx.get();
        try {
            tLocaltx.set(null);
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                tx.rollback();
            }
        } catch (HibernateException e) {
            //throw new InfrastructureException(e);
        }
    }

    private static Session openSession() throws HibernateException {
        return getSessionFactory().openSession();
    }

    private static SessionFactory getSessionFactory() throws HibernateException {
        return sessionFactory;//SingletonSessionFactory.getInstance();
    }
}

 

  在Dao中:

  打开一个session后,不关闭这个session,否则在级联的情况下可能会产生org.hibernate.LazyInitializationException:

所以定义一个过滤器:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CloseSessionFilter implements Filter {
	Log logger = LogFactory.getLog(this.getClass());
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	protected FilterConfig config;
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.config = arg0;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain)
		throws IOException, ServletException {
		// TODO Auto-generated method stub
		try{
			chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
		}
		finally{
			try{
				HibernateUtil.commitTransaction();
			}catch (Exception e){
				HibernateUtil.rollbackTransaction();
			}finally{
				HibernateUtil.closeSession();
			}   
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		this.config = null;
	}

}

  

    在web.xml中配置:

<filter>
	<filter-name>closeSessionFilter</filter-name>
		<filter-class>
			utils.CloseSessionFilter
		</filter-class>
</filter>
<filter-mapping>
		<filter-name>closeSessionFilter</filter-name>
		<url-pattern>/*</url-pattern>
</filter-mapping>

 

而到了spring 中,在web.xml配置:

<filter>
	<filter-name>openSession</filter-name>
	<filter-class>
	org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
	</filter-class>
</filter>

 

分享到:
评论

相关推荐

    HibernateUtil分装完整版HQL查询

    标题"HibernateUtil分装完整版HQL查询"暗示了这是一个关于使用HibernateUtil工具类来封装和执行HQL(Hibernate Query Language)查询的教程或代码示例。描述中的重复信息进一步强调了这个主题,意味着我们将探讨如何...

    HibernateUtil 分页 增删改查 封装

    HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装

    hibernate入门实例封装了HibernateUtil

    【标题】:Hibernate入门实例——基于HibernateUtil的数据库操作封装 在Java开发中,Hibernate作为一个强大的对象关系映射(ORM)框架,极大地简化了数据库操作。本实例将深入浅出地介绍如何使用Hibernate进行基本...

    06_传智播客hibernate教程_完善HibernateUtil类及hql查询入门

    本教程聚焦于“完善HibernateUtil类及HQL查询入门”,让我们深入探讨这两个关键概念。 首先,`HibernateUtil` 类是 Hibernate 教程中常见的一种工具类,它的主要作用是提供对 Hibernate 框架的简单封装,以方便进行...

    HibernateUtil工具类

    HibernateUtil工具类

    hibernate 一对多测试工程

    Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Class class1 = new Class(); // set class1 properties List&lt;Student&gt; students =...

    HibernateUtil.java Hibernate5.2.1

    Hibernate5.2.1 的工具类 创建session 和 sessionFactory

    java util工具类

    HibernateUtil.java HibernateUtils.java HttpRequester.java HttpRespons.java HttpUtil.java MD5Util.java Pagination.java PropertiesUtil.java RegUtil.java StringUtil.java UploadUtil.java UUIDUtils.java

    Hibernate工具类

    `HibernateUtil`工具类就是对Hibernate框架功能的一种封装,简化了对数据库的操作。 在`HibernateUtil`工具类中,常见的方法有以下几类: 1. **初始化SessionFactory**: SessionFactory是Hibernate的核心组件,它...

    hibernateUtil.txt

    欢迎大家咨询,我会尽量去与大家讲解,希望对你们有所帮助

    对DAO编写单元测试源代码

    } &lt;br&gt; public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...

    基于泛型的通用Dao接口和hibernate的实现

    return HibernateUtil.getSession().createCriteria(clazz).list(); } @SuppressWarnings("unchecked") public List&lt;T&gt; findList(int pageNo, int pageSize) { return HibernateUtil.getSession()....

    hibernate学习笔记

    - **编写 HibernateUtil 工具类**:用于获取SessionFactory和Session,简化操作。 - **编写数据访问层**:使用HibernateUtil,实现CRUD(创建、读取、更新、删除)操作。 2. **Domain Object 规范** - **无参...

    hibernate 的各种操作

    Session session = HibernateUtil.currentSession(); // 获取当前会话 Transaction tx = null; // 事务 Users po = new Users(); // 实体对象 po = transCommerceInfoVOtoPO(vo, po); // 将 VO 转换为 PO try...

    案例课程B-S架构-1期 详细设计书9-公告管理模块.pdf

    - 模型层:在HibernateUtil中增加了公告新增的业务逻辑方法,接收封装用户输入的实体对象。 4. **公告删除** - 界面层:删除操作在公告列表页面中进行,无单独的删除界面。若用户无权限,会显示bbc_nomodify.jsp...

    六种方式实现hibernate查询

    s=HibernateUtil.getSession(); String hql="from Admin as admin where admin.aname=:name"; Query query=s.createQuery(hql); query.setString("name", name); List&lt;Admin&gt; list=query.list(); for(Admin ...

    案例课程B-S架构-1期 详细设计书18-审核批示模块.pdf

    控制层的`updateShen.jsp`逻辑页面接收用户输入,调用`HibernateUtil`中的`updateshenhe()`方法进行更新操作,并根据执行结果决定页面跳转。 3. **申请的审核**:未提供详细设计,通常涉及用户提交审批申请的功能。...

Global site tag (gtag.js) - Google Analytics