OpenSessionInView模式

Posted Onlyだ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenSessionInView模式相关的知识,希望对你有一定的参考价值。

首先搭建建构

引入jar包

 

创建实体类  Emp.java

public class Emp {
    private Integer empId;//员工ID
    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;
    }
    
}

配置大配置

<hibernate-configuration>
   <session-factory>
       <!-- 1.连接数据库的语句 -->
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="connection.username">scott</property>
        <property name="connection.password">0123</property>
        
        
        <!-- 输出所有 SQL 语句到控制台。 -->
        <property name="hibernate.show_sql">true</property> 
        
        <!-- 在 log 和 console 中打印出更漂亮的 SQL。 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 方言 -->
        <property name="hibernate.dialect">    org.hibernate.dialect.Oracle10gDialect</property>
    
         <!-- hbm2ddl --> 
         <property name="hibernate.hbm2ddl.auto">update</property>

         <!-- 支持getCurrentSession的 属性配置 -->
         <property name="hibernate.current_session_context_class">thread</property>
       <!-- 关联小配置 -->
       
      <!-- <mapping resource="cn/happy/entity/Project.hbm.xml"/> --> 
       <mapping resource="entity/Emp.hbm.xml"/>
       
   </session-factory>

</hibernate-configuration>
    

配置  小配置

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="entity">
    <class name="Emp" table="Emp2">
        <id name="empId" column="EMPID">
            <generator class="native"></generator>
        </id>
        <property name="empname" type="string" column="empname"></property>
        
        <!-- 多对多 -->
        <!-- <set name="pros" table="ProEmp">
            <key column="nid"></key>
            <many-to-many class="Project" column="pid"></many-to-many> 
        </set>-->
    </class>

</hibernate-mapping>

创建HibernateUtil工具类

public class HibernateUtil {
    
    private static final ThreadLocal sessionTL = new ThreadLocal(); 
    private static Configuration configuration;
    //
    private  static final SessionFactory sessionFactory;
    static{
        try {
            configuration=new Configuration().configure();
            sessionFactory=configuration.buildSessionFactory();
            
            
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
        
    }
    public static Session getSession() {
        
        Session session = (Session)sessionTL.get();
        if(session==null)
        {
            session = sessionFactory.openSession();
            sessionTL.set(session);
        }
        return session;
    }
    public static void closeSession()
    {
        Session session = (Session)sessionTL.get();
        sessionTL.set(null);
        session.close();
        
    }

}

搭建Dao

package dao;

import java.io.Serializable;

import util.HibernateUtil;


public class Mydao {
    public Object  get(Class clazz,Serializable id){
           System.out.println("dao\\t"+HibernateUtil.getSession());
           Object result= HibernateUtil.getSession().load(clazz, id);
           return result;
    }

}

biz层

public class Hibernatebiz {
    Mydao dao=new Mydao();
    public Object get(Class clazz,Serializable id){
          // Transaction tx = HibernateUtil.getSession().beginTransaction();
           Object obj= dao.get(clazz, id);
           System.out.println("==============================================");
         //  tx.commit();
          // HibernateUtil.closeSession();
           return obj;
    }

}

filter类

public class MyFilter implements Filter{

    public void destroy() {
        // TODO Auto-generated method stub
        
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        Session session;
        Transaction tx=null;
        try {
            session=HibernateUtil.getSession();
            tx=session.beginTransaction();
            chain.doFilter(request, response);
            tx.commit();
            
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }
        finally{
            HibernateUtil.closeSession();
        }
        
    }

最后编写测试类

public class H_01Test {
    @Test
    public void addTest(){
        Hibernatebiz biz=new Hibernatebiz();
        Object object = biz.get(Emp.class,1);
        Emp emp=(Emp)object;
        System.out.println(emp.getEmpname());
        
    }

}

结果:

 

以上是关于OpenSessionInView模式的主要内容,如果未能解决你的问题,请参考以下文章

OpenSessionInView

OpenSessionInview

OpenSessionInview

OpensessionInView的理解

Hibernate__OpenSessionInView解决懒加载问题

open Session In View模式