天天看點

Hibernate-ORM:09.Hibernate中的getCurrentSession()------------吾亦無他,唯手熟爾,謙卑若愚,好學若饑-------------

------------吾亦無他,唯手熟爾,謙卑若愚,好學若饑-------------

本篇部落格将講述,以優雅的方式建立session對象,我将會說明優點,并提煉成工具類

優點:

  1.無需手動關閉session

  2.提高了性能,不需要頻繁的建立session對象

說明:

  雖然getCurrentSession()底層調用了openSession(),但是做了單例操作,是以性能更高,更安全

工具類:

package cn.dawn.util;

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

/**
 * Created by Dawn on 2018/5/30.
 */
public class SessionFactoryUtil {
    private static Configuration configuration;//加載核心配置檔案
    private static SessionFactory factory;//單例對象

    //在類加載的時候,加載靜态代碼塊
    static {
        configuration=new Configuration().configure();//預設加載根目錄下的hibernate.cfg.xml
        factory=configuration.buildSessionFactory();
    }

    //通過sessionfactory建立session
    /*設定同步,保證線程安全*/
    public static synchronized Session getCurrentSession(){
        return factory.getCurrentSession();
        /*不能直接使用,需要在核心配置檔案中加入一個節點*/
        /*<property name="current_session_context_class">thread</property>*/
    }
}      

另外需要在hibernate.hbm.xml中配置一個節點:

<property name="current_session_context_class">thread</property>      

簡單的使用案例:

package cn.dawn.day03;

import cn.dawn.day03.entity.Teacher;
import cn.dawn.util.SessionFactoryUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * Created by Dawn on 2018/5/25.
 */
/*分頁*/
public class Test0120180530Page {
    /*事物*/
    Transaction tr=null;
    /*session*/
    Session session=null;




    @Test
    /**
     * 分頁
     *
     * 01.查詢總記錄數
     * 02.每頁顯示的資料
     * 03.總頁數
     */
    public void t1Page(){
        String hql="select count(*) from Teacher";//會傳回Long類型
        int counts=((Long)session.createQuery(hql).uniqueResult()).intValue();
        /*頁大小*/
        int pageSize=2;
        /*總頁數*/
        int totalPages=(counts%pageSize==0)?(counts/pageSize):(counts/pageSize+1);
        /*顯示第二頁内容*/
        int pageIndex=2;
        hql="from Teacher";
        Query query = session.createQuery(hql);;
        /*從哪一條開始查*/
        query.setFirstResult((pageIndex-1)*pageSize);
        /*設定頁大小*/
        query.setMaxResults(pageSize);
        List<Teacher> teachers = query.list();
        for (Teacher t:teachers) {
            System.out.println(t);
        }

    }


    /*在執行之前加載配置,運作事物*/
    @Before
    public void beforeTest(){

        /*使用工具類*/
        /*建立session*/
        session = SessionFactoryUtil.getCurrentSession();
        /*建立事物*/
        tr = session.beginTransaction();
    }

    /*在執行之後,送出事物,關閉session*/
    @After
    public void afterTest(){
        /*送出事物*/
        /*tr.commit();*/
        /*關閉session*/
        /*session.close();*/
    }
}      

繼續閱讀