創建Hibernate獲取Session的工具類

package com.ckinghan.utils;

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

public class HibernateUtils {
    //定義SessionFactory變量
    private static SessionFactory buildSessionFactory;
    //當虛擬機加載時,加載配置文件,並創建SessionFactory
    static{
        Configuration configuration = new Configuration().configure();
        buildSessionFactory = configuration.buildSessionFactory();

        //創建任務,當虛擬機關閉時,釋放SessionFactory
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("當虛擬機關閉時,釋放SessionFactory");
                buildSessionFactory.close();
            }
        }));

    }

    //返回一個的Session
    public static Session openSession(){
        return buildSessionFactory.openSession();
    }

    //獲取與當前線程綁定的Session
    public static Session getCurrentSession(){
        return buildSessionFactory.getCurrentSession();
    }
}

編寫測試類:

package com.ckinghan.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.junit.Test;

import com.ckinghan.bean.User;
import com.ckinghan.utils.HibernateUtils;

public class HibernateUtilsTest {

    /**
     * 測試HibernateDBUitls工具類
     */
    @Test
    public void hibernateDBUtilsTest(){
        //通過工具類獲取綁定當前線程的Session
        Session session = HibernateUtils.getCurrentSession();
        //啓動事務
        Transaction transaction = session.beginTransaction();
        //通過Session創建Criteria
        Criteria criteria = session.createCriteria(User.class);
        //通過list方法執行SQL語句獲取結果集
        List<User> list = criteria.list();
        //輸出查詢結果
        System.out.println(list);
        //提交事務
        transaction.commit();
    }
}

測試結果如下 :

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: 
    select
        this_.id as id0_0_,
        this_.userName as userName0_0_,
        this_.password as password0_0_ 
    from
        user this_
[User [id=1, userName=0, password=password123], User [id=2, userName=0, password=password123]]
當虛擬機關閉時,釋放SessionFactory
發佈了153 篇原創文章 · 獲贊 69 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章