本文共 3329 字,大约阅读时间需要 11 分钟。
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; }} oracle.jdbc.OracleDriver jdbc:oracle:thin:@localhost:1521:orcl scott 0123 true true org.hibernate.dialect.Oracle10gDialect update thread
public class HibernateUtil { private static final ThreadLocal sessionTL = new ThreadLocal(); private static Configuration configuration; private static 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(); }} 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; }} public class HibernateBiz { MyDao dao = new MyDao(); public Object get(Class clazz, Serializable id) { Object obj = dao.get(clazz, id); System.out.println("=============================================="); return obj; }} 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()); }} 转载地址:http://mcpfk.baihongyu.com/