Open Session In View模式的主要思想是:在用户的每一次请求过程始终保持一个Session对象打开着

实现步骤:

步骤一.创建一个Web项目,创建包cn.happy.util,创建HibernateUtil工具类

public class HibernateUtil{
    private static final ThreadLocal sessionTL=new ThreadLocal();
    private static Configuration cfg;
    private final static SessionFactory factory;
    static{
         cfg=new Configuration().configure();
         factory=cfg.buildSessionFactory();
    }
    public static Session currentSession()
   {
         Session session=(Session)sessionTL.get();
         if(session==null)
        {
            session=factory.openSession();
            sessionTL.set(session);
        }
            return session;
   }
   public static void closeSession()
  {
     Session session=(Session) sessionTL.get();
     sessionTL.set(null);
     session.close();
  }

}

步骤二.创建包cn.happy.entity,创建实体类Emp和Emp.hbm.xml小配置文件

public class Emp {
    private Integer empId;
    private String empName;
    public Integer getEmpId() {
        return empId;
    }
    public void setEmpId(Integer empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.happy.entity">
    <class name="Emp" table="Emps">
    <id name="empId">
        <generator class="native">
        </generator>
    </id>
    <property name="empName"></property>
    <!-- 植入一个Dept对象           多对一 -->
    </class>
</hibernate-mapping>

步骤三.创建包cn.happy.Dao创建类MyDao

public class MyDao{
     public Object get(Class classz,Serializable id)
    {
       Object obj=HibernateUtil.currentSession().load(classz,id);
       return obj;
    }      

}    

步骤四.创建包cn.happy.biz创建类MyBiz

public class MyBiz
{
   public Object get(Class classz,Serializable id)
   {
        MyDao dao=new MyDao();
        Obejct obj=dao.get(classz,id);
        return obj;
   }
}

步骤五.创建cn.happy.filter包创建类MyFilter,实现Filter接口,重写doFilter方法

public void doFilter(ServletRequet request,ServletResponse response,FilterChain arg2) throw IOException,ServletExption{
    Session session=null;
    Transaction tx=null;
    session=HibernateUtil.currentSession();
    tx=session.beginTransaction();
    arg2.doFilter(request,response);
    tx.commit();
    HibernateUtil.closeSession();
}

步骤六.创建大配置文件hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings 数据库连接设置 -->
        <!-- 驱动类 -->
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <!-- url地址 -->
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="connection.username">Hibernate</property>
        <property name="connection.password">orcl</property>
        <!-- SQL dialect (SQL 方言) -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <!--在控制台打印后台的SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 格式化显示SQL -->
        <!-- <property name="format_sql">true</property> -->
        <!-- 自动生成表 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 关联小配置 -->
        <mapping resource="cn/happy/entity/Emp.hbm.xml" />
    </session-factory>
</hibernate-configuration>

步骤七.在web.xml文件中配置fileter

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  <filter-name>openSessionInview</filter-name>
  <filter-class>cn.happy.Filter.MyFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>openSessionInview</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

然后我们在index.xml文件中来显示数据

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="org.hibernate.Session"%>
<%@page import="cn.happy.Util.HibernateUtil" %>
<%@page import="org.hibernate.Transaction" %>
<%@page import="cn.happy.Biz.MyBiz" %>
<%@page import="cn.happy.entity.Emp" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>OpenSessionInview</title>

  </head>

  <body>
    <%

        MyBiz biz=new MyBiz();    <!--拿到id为1的员工,在页面显示名字-->
        Object object = biz.get(Emp.class, 1);
        Emp emp=(Emp)object;

     %>
     <%=emp.getEmpName() %>
  </body>
</html>

这样我们就实现了OpenSessionInview

OpenSessionInview的更多相关文章

  1. SpringMVC学习系列-后记 开启项目的OpenSessionInView

    在系列的 SpringMVC学习系列(12) 完结篇 的示例项目中,由于当时考虑到OpenSessionInView会对性能有一定的影响,所以就没有配置项目的OpenSessionInView.在ma ...

  2. 细说OpenSessionInView问题

    [环境参数] 环境:SSH框架 [问题描述]  NoSession问题 HibernateTemplate对象提供的方法如果使用“延迟加载”,Session对象的管理不受开发者控制,此时如果在表现层获 ...

  3. SSH第一篇【整合SSH步骤、OpenSessionInView】

    前言 到目前为止,Struts2.Hibernate.Spring框架都过了一遍了.也写过了Spring怎么与Struts2整合,Spring与Hibernate整合-本博文主要讲解SSH的整合 整合 ...

  4. [转]java框架spring中的opensessioninview有什么作用

    在hibernate中使用load方法时,并未把数据真正获取时就关闭了session,当我们真正想获取数据时会迫使load加载数据,而此时 session已关闭,所以就会出现异常. 比较典型的是在MV ...

  5. [转]OpenSessionInView模式

    OpenSessionInView模式解决的问题:   * hibernate事物边界问题   * 因session关闭导致hibernate延迟加载例外的问题 事物边界:     一个事物的完成应该 ...

  6. [转]Java程序员从笨鸟到菜鸟之(八十三)细谈Spring(十二)OpenSessionInView详解及用法

    首先我们来看一下什么是OpenSessionInView?    在hibernate中使用load方法时,并未把数据真正获取时就关闭了session,当我们真正想获取数据时会迫使load加载数据,而 ...

  7. 详细解析Spring事务的配置和OpenSessionInview的作用

    1.事务的特性   原子性:事务中的操作是不可分割的一部分   一致性:要么同时成功,要么同时失败(事务执行前后数据保持一致)   隔离性:并发互不干扰     持久性:事务一旦被提交,它就是一条持久 ...

  8. (转)Spring提供的CharacterEncoding和OpenSessionInView功能

    http://blog.csdn.net/yerenyuan_pku/article/details/52902282 前面我们以一种更加优雅的方式集成了Spring4.2.5+Hibernate4. ...

  9. openSessionInView的使用原理及性能分析

    看到好多项目中用到了openSessionInView,这种做法无非是开发方便,能够在JSP页面中操作数据库层方面的业务. 下边说下openSessionInView的使用方法及性能问题. 使用: 1 ...

随机推荐

  1. ssh框架搭建的基本步骤(以及各部分作用)

    ssh框架搭建的基本步骤(以及各部分作用)     一.首先,明确spring,struts,hibernate在环境中各自的作用.   struts: 用来响应用户的action,对应到相应的类进行 ...

  2. Excel里生成GUID

    Private Declare Function CoCreateGuid Lib "ole32" (id As Any) As Long    Private Function ...

  3. HttpClient示例

    <%@page import="com.sun.xml.ws.client.BindingProviderProperties"%> <%@page conten ...

  4. OC笔记

    self的概念:指向了当前对象(方法的调用者) self的用途 可以利用  self -> 成员变量名  访问当前对象内部的成员变量 [self 方法名];  调用其他对象方法或者类方法 所有继 ...

  5. [Android]Activity跳转传递任意类型的数据、Activity为SingleTask时代替StartActivityForResult的解决方案

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/4389674.html 需求:在ActivityA跳转到Acti ...

  6. Android Animation学习(六) View Animation介绍

    Android Animation学习(六) View Animation介绍 View Animation View animation系统可以用来执行View上的Tween animation和F ...

  7. AndRoid studio创建APP图标

    打开---File----New----Image asset 注意:在design页面可能没有image asset选项!必须在其他编辑页面! 这就打开了图标设置页面,找到自己想要的图标就好!下面框 ...

  8. 关于OC中的block自己的一些理解(一)

    一.关于block 1.block的作用:保存一段代码. 2.苹果官方推荐的一种语法,类似于C语言的函数,但是比函数更加灵活. 3.^是block语法的标识. 二.block的用法 1)无返回值无参数 ...

  9. 让我们喝喝下午茶,聊聊AJAX和JSON

    1.AJAX     [1] AJAX简介         > 全称:Asynchronous JavaScript And XML         > 直译:异步的JavaScript和 ...

  10. 测试必备技能系列1 :通过mysql命令进行脚本数据导入

    老徐,分享测试项目中实际能解决问题的干货!   今日分享: 如何通过mysql命令行,导入mysql脚本文件数据?   ----- 解决实际的问题: 工作过程中,经常需要导入mysql脚本文件 很多同 ...