hibernate中OpenSessionInView方式的实现

OpenSessionInView:由于Hibernate引入了Lazy Load特性,使得脱离Hibernate的Session周期的对象如果再想通过getter方法取到其关联对象的值,Hibernate会抛出一个LazyLoad的Exception。所以为了解决这个问题,使得Hibernate的Session的生命周期变长。

步骤:

一、创建一个web Ojbect 项目

二、数据库为MySql

CREATE TABLE `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(50) NOT NULL,

  `birthday` datetime DEFAULT NULL,

  `sex` varchar(50) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=gb2312;

 

三、在MyEclipse 中添加hibernate3x jar文件,或者通过MyEclipse的支持方式加入

 

四、更改hibernate.cfg.xml 文件配置 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
    <session-factory>
    	<property name="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property>
    	<property name="hibernate.connection.url">jdbc:mysql:///test</property>
    	<property name="hibernate.connection.username">root</property>
    	<property name="hibernate.connection.password">root</property>
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    	<property name="hibernate.show_sql" >true</property>
    	<property name="hibernate.format_sql" >true</property> 
    	<mapping resource="com/entity/User.hbm.xml" />
    </session-factory>	
</hibernate-configuration>

五、创建一个Hibernate获取session的工具类HibernateBase.java

  

package com.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public final class HibernateBase {
	private static SessionFactory sessionFactory;
	//创建一个线程本地变量 
	private static ThreadLocal threadLocal = new ThreadLocal();
	private HibernateBase(){}
	//本地线程添加session
	public static Session getThreadLocal(){
		Session session = (Session) threadLocal.get();
		if (session == null) {
			session = getSession();
			threadLocal.set(session);
		}
		return session;
	}
	public static SessionFactory getSessionFactory(){
		if (sessionFactory==null) {
			Configuration cf = new Configuration();
			cf.configure();
			sessionFactory = cf.buildSessionFactory();
		}
		return sessionFactory;
	}
	
	public static Session getSession(){
		return getSessionFactory().openSession();
	}
}

六、创建实体对象 

   

package com.entity;
import java.util.Date;
public class User {
	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	private Date birthday;
	private String sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
}

七、创建实体映射文件User.hbm.xml

<?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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.entity.User" table="user">
       <!—二级缓存   <cache usage="read-only"/> -->
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native"></generator>
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="50" not-null="true" />
        </property>
        <property name="birthday" type="java.util.Date">
        	<column name="birthday"></column>
        </property>
        <property name="sex" type="java.lang.String">
        	<column name="sex" length="50" not-null="true"></column>
        </property>
    </class>
</hibernate-mapping>

八、创建一个通用的dao文件,HiberanteDaoImpl.java

package com.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import com.util.HibernateBase;
public class HiberanteDaoImpl { 
	private static Session session;
	/**
	 * openSessionInView方式采用
	 * @param object
	 */
	public void addThread(Object object){
		try {
		    session =  (Session) HibernateBase.getThreadLocal();
			session.save(object);
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}
	/**
	 * openSessionInView方式采用 删除
	 * @param object
	 */
	public void delThread(Object object){
		try {
		    session =  (Session) HibernateBase.getThreadLocal();
			session.delete(object);
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}
}

 

 

 

九、创建过滤器:主要采用过滤的方式进行OpenSessionInView.java

package com.web;
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 org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.util.HibernateBase;

public class OpenSessionInView implements Filter {
@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		Session session = null;
		Transaction tx = null;
		try {
			session = (Session) HibernateBase.getThreadLocal();
			tx = session.beginTransaction();//事物开始 在视图层创建事物
			arg2.doFilter(arg0, arg1);
			tx.commit();
			session.close();
		 
		} catch (HibernateException e) {
			if (tx!=null) {
				tx.rollback();
			}
		}finally{
			//不能关闭session 
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}

  

十、 创建servlet文件UserServlet.java

  

package com.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.impl.HiberanteDaoImpl;
import com.entity.User;
public class UserServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//添加user对象 然后再删除 这里就不做视图的创建了,通过servlet简单演示
		User user = new User();
		user.setName("abc");
		user.setBirthday(new Date());
		user.setSex("男");
		HiberanteDaoImpl dao  = new HiberanteDaoImpl();
		dao.addThread(user);  //添加
		dao.delThread(user); //删除	
		out.flush();
		out.close();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}

十一、 打开浏览器输入http://localhost:8080/hibernate/userServlet

相关推荐