Hibernate第十一篇【配置C3P0數據庫鏈接池、線程Session】

Hibernate鏈接池

Hibernate自帶了鏈接池,可是呢,該鏈接池比較簡單..而Hibernate又對C3P0這個鏈接池支持…所以咱們來更換Hibernate鏈接池爲C3P0數據庫

查看Hibernate自帶的鏈接池

咱們能夠經過Hibernate.properties文件中查看Hibernate默認配置的鏈接池markdown

hibernate.properties的配置文件能夠在\project\etc找到session

Hibernate的自帶鏈接池啥都沒有,就一個鏈接數量爲1ide

這裏寫圖片描述


查看Hibernate對C3P0的支持

  • #hibernate.c3p0.max_size 2 最大鏈接數
  • #hibernate.c3p0.min_size 2 最小鏈接數
  • #hibernate.c3p0.timeout 5000 超時時間
  • #hibernate.c3p0.max_statements 100 最大執行的命令的個數
  • #hibernate.c3p0.idle_test_period 3000 空閒測試時間
  • #hibernate.c3p0.acquire_increment 2 鏈接不夠用的時候, 每次增長的鏈接數
  • #hibernate.c3p0.validate false

這裏寫圖片描述

修改Hibernate鏈接池

咱們在hibernate.cfg.xml中配置C3p0,讓C30P0做爲Hibernate的數據庫鏈接池測試

查找Hibernate支持的鏈接池組件有什麼ui

這裏寫圖片描述

既然找到了,那麼咱們在hibernate.cfg.xml中配置對應的類就和相關配置就好了spa

<!-- 【鏈接池配置】 -->
        <!-- 配置鏈接驅動管理類 -->
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <!-- 配置鏈接池參數信息 -->
        <property name="hibernate.c3p0.min_size">2</property>
        <property name="hibernate.c3p0.max_size">4</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <property name="hibernate.c3p0.max_statements">10</property>
        <property name="hibernate.c3p0.idle_test_period">30000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>

線程Session

咱們建立Session的時候,有兩個方法hibernate

  • openSession()【每次都會建立新的Session】
  • getCurrentSession()【獲取當前線程的Session,若是沒有則建立】

通常地,咱們使用線程Session比較多線程

若是要使用getCurrentSession(),須要在配置文件中配置:code

<!--配置線程Session-->
        <property name="hibernate.current_session_context_class">thread</property>

測試數據

@Test
    public void testSession() throws Exception {
        //openSession: 建立Session, 每次都會建立一個新的session
        Session 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,綁定到線程
        Session session4 = sf.getCurrentSession();// 從當前訪問線程獲取session
        System.out.println(session3 == session4);

        // 關閉 【以線程方式建立的session,能夠不用關閉; 線程結束session自動關閉】
        //session3.close();
        //session4.close(); 報錯,由於同一個session已經關閉了!
    }
相關文章
相關標籤/搜索