hibernate的session和線程綁定

一.說明

實現一個線程只有一個session對象。

二.範例

1.代碼塊

(1)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
                SessionFactory的作用就是創建session-factory對象。
                Session對象是hibernate中操作數據庫的核心對象
         -->
    <session-factory>
        <!-- 注意:配置session-factory三要素
            第一要素:連接數據庫的信息
            第二要素:hibernate的可選配置
            第三要素:映射文件的位置
         -->
        <!-- 配置數據庫連接池 -->
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <!-- 第一部分:連接數據庫的信息 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db7</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!-- 設置數據庫的方言 -->
        <property name="hibernate.dialect org.hibernate.dialect.MySQLDialect"></property>
        <!-- 第二部分:hibernate的可選配置 -->
        <!-- 2.1配置顯示hibernate的自動生成sql語句 -->
<!--        <property name="hibernate.show_sql">true</property>-->
        <!-- 2.2使用格式化sql語句打印到控制檯 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 2.3配置hibernate何種方式生成DDL語句 -->
        <!-- update表示檢測是否實體類的映射配置和數據庫的表結構一致,如果不一致,則更新表結構 -->
        <!--
        SQL結構化語言分類:一共6個部分
         DDL:
         DML:
         DQL:
         DCL:數據控制語言(權限控制)
         CCL:遊標控制語言(指針控制)
         TPL:事務處理語言(事務控制)
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 把session和線程綁定,從而實現一個線程只有一個session -->
        <property name="hibernate.current_session_context_class">thread</property>
        <!-- 第三部分:映射配置文件的位置 -->
        <mapping resource="cn/dao/CustomerMapping.xml"></mapping>
    </session-factory>
</hibernate-configuration>

(2)工具類

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 封裝一個Hibernate對象的工具欄
 */
public class HibernateUtil2 {
    private static SessionFactory sessionFactory;
    static {
        try {
            //加載hibernate主配置文件
            Configuration cfg = new Configuration();
            cfg.configure("hibernateConfig.xml");//設置加載配置文件
            //獲取一個sessionFactory對象
            sessionFactory = cfg.buildSessionFactory();
        }catch (ExceptionInInitializerError e){
            throw new ExceptionInInitializerError("初始化工廠失敗,請檢查配置文件");
        }
    }
    //只要使用open的方法,每次得到的是新的session
    public static Session openSession(){
        return sessionFactory.openSession();
    }
    //一個線程只有一個session對象
    public static Session getCurrentSession(){
        //注意:只有線程和session綁定後,才能使用此方法。
        return sessionFactory.getCurrentSession();
    }
}

(3)測試類

import cn.domain.Customer;
import cn.utils.HibernateUtil;
import cn.utils.HibernateUtil2;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
/**
 * 測試一個線程保持一個session
 */
public class HibernateTest03 {
    @Test
    public void test01()throws Exception{
        Session session = HibernateUtil2.getCurrentSession();
        Session session2 = HibernateUtil2.getCurrentSession();
        System.out.println(session == session2);
    }
    /**
     * 使用線程綁定的session不能關閉session
     * @throws Exception
     */
    @Test
    public void test02()throws Exception {
        Customer customer = new Customer();//瞬時狀態
        customer.setCustName("liming");
        Session session = HibernateUtil2.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        session.save(customer);//持久化狀態
        transaction.commit();
//        session.close();//session在提交事務之後,自動進行關閉操作
    }
}

2.範例

(1)xml配置文件

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-C5ynbrOp-1589608400024)(https://uploader.shimo.im/f/khEpFrPtJPglLyTw.png!thumbnail)]

(2)工具類

圖片

(3)測試類

圖片

三.源碼

day02.rar

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章