(21)項目中Hibernate Session的管理方式

來源:互聯網
上載者:User

標籤:hibernate


1、openSession和getCurrentSession的區別

package com.rk.hibernate.cache;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.junit.Test;public class App_SessionInProject{private static SessionFactory sf;static{sf = new Configuration().configure().addClass(Department.class).addClass(Employee.class).buildSessionFactory();}@Testpublic void testSession(){//openSession:  建立Session, 每次都會建立一個新的sessionSession session1 = sf.openSession();Session session2 = sf.openSession();System.out.println(session1 == session2);session1.close();session2.close();//getCurrentSession 建立或者擷取session// 線程的方式建立session  // 一定要配置:<property name="hibernate.current_session_context_class">thread</property>Session session3 = sf.getCurrentSession();Session session4 = sf.getCurrentSession();System.out.println(session3 == session4);// 關閉 【以線程方式建立的session,可以不用關閉; 線程結束session自動關閉】//session3.close();//session4.close(); 報錯,因為同一個session已經關閉了!}}


2、strut2項目中使用Hibernate Session


hibernate.cfg.xml

<!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><!-- 資料庫連接資訊 --><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql:///hib_demo</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><property name="hibernate.show_sql">true</property><property name="hibernate.hbm2ddl.auto">update</property><!-- session建立方式 --><property name="hibernate.current_session_context_class">thread</property><!-- 載入映射 --><mapping resource="com/rk/entity/Department.hbm.xml"/><mapping resource="com/rk/entity/Employee.hbm.xml"/></session-factory></hibernate-configuration>

HibernateUtils.java

package com.rk.utils;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtils {// 初始化SessionFactoryprivate static SessionFactory sf;static {sf = new Configuration().configure().buildSessionFactory();}// 建立(擷取)Sessionpublic static Session getSession() {// 線程的方式建立session,必須要配置// 可以不用關閉,會自動關。return sf.getCurrentSession();}}

SessionInterceptor.java

package com.rk.interceptor;import org.hibernate.Session;import com.rk.utils.HibernateUtils;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;/** * Session管理攔截器: *   當訪問action的時候,建立session;  *  action ---> service  --> dao 【擷取的是這裡建立的session】 *  * */public class SessionInterceptor extends AbstractInterceptor {@Overridepublic String intercept(ActionInvocation invocation) throws Exception {try {// 1. 先建立SessionSession session = HibernateUtils.getSession();// 2. 開啟事務session.beginTransaction();// 3. 執行ActionString result = invocation.invoke();// 4. 提交事務session.getTransaction().commit();  // 不需要關閉session// 返回結果檢視return result;} catch (Exception e) {e.printStackTrace();return "error";}}}

DepartmentDao.java

package com.rk.dao;import com.rk.entity.Dept;import com.rk.utils.HibernateUtils;public class DepartmentDao {/** * 主鍵查詢 */public Department findById(int id){// 擷取session, 執行操作return (Department) HibernateUtils.getSession().get(Department.class, id);}}


3、HibernateUtil.java

package com.rk.hibernate.utils;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 sf;private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();static{Configuration cfg = new Configuration();sf = cfg.configure().buildSessionFactory();}public static Session getSession(){Session session = threadSession.get();try{// Open a new Session, if this thread has none yetif (session == null){session = sf.openSession();threadSession.set(session);}}catch (HibernateException e){throw new RuntimeException(e);}return session;}public static void closeSession(){try{Session session = threadSession.get();threadSession.set(null);if (session != null && session.isOpen()){session.close();}}catch (HibernateException e){throw new RuntimeException(e);}}public static void beginTransaction(){Transaction tx = threadTransaction.get();try{if (tx == null){tx = getSession().beginTransaction();threadTransaction.set(tx);}}catch (HibernateException e){throw new RuntimeException(e);}}public static void commitTransaction(){Transaction tx = threadTransaction.get();try{if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){tx.commit();threadTransaction.set(null);}}catch (HibernateException e){rollbackTransaction();}}public static void rollbackTransaction(){Transaction tx = threadTransaction.get();try{if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){threadTransaction.set(null);tx.rollback();}}catch (HibernateException ex){throw new RuntimeException(ex);}finally{closeSession();}}}


過濾器

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)        throws IOException, ServletException {    try     {        chain.doFilter(request, response);        HibernateUtil.commitTransaction();    } finally {        HibernateUtil.closeSession();    }}


DAO

public void execute() {     // Get values from request     try {         HibernateUtil.beginTransaction();         Session session = HibernateUtil.getSession();         // Forward to Success.jsp page     } catch (HibernateException ex) {         throw new InfrastructureException(ex);     } catch (Exception ex) {         // Throw application specific exception     } }





(21)項目中Hibernate Session的管理方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.