在使用MyEclipse創建Hibernate之後都會自動生成一個HibernateSessionFactory,這個類的主要功能是進行數據庫連接對象(Session)的取得與關閉。
在以後的開發之中,很少會在代碼裏面去關注:Configuration、SessionFactory等操作。包括如何連接如何創建工廠都會被實際的其它操作所取代。用戶最關注的就是如何進行數據的CRUD操作。
1 ThreadLocal類的作用
但是在這個HibernateSessionFactory裏面有一個重要的操作實現:java.lang.ThreadLocal<T>
,這個類是一個幫助我們解決引用問題的操作類。這個類有如下兩個重要的操作方法:
(1)設置對象內容:public void set(T value)
(2)取得對象內容:public T get()
下面通過一個實驗來進行實際的使用分析。
範例:傳統做法
package org.lks.test;
public class News {
private String title;
}
package org.lks.test;
public class Message {
public void print(News vo){
System.out.println(vo.getTitle());
}
}
傳統的開發做法,是如果Message要想輸出News類對象的內容,那麼必須要在Message類裏面傳遞一個News類對象的引用纔可以進行處理。
範例:標準處理
package org.lks.test;
public class TestMessage {
public static void main(String[] args) {
News vo = new News();
vo.setTitle("hhy big fool");
Message msg = new Message();
msg.print(vo);
}
}
整個代碼使用了一個明確的對象引用操作的方式完成。
那麼如果說此時使用的是ThreadLocal類,處理的形式就可以發生一些變化,不再需要由用戶自己來處理明確的引用關係。
範例:定義ThreadUtil類,這個類主要負責傳送ThreadLocal
package org.lks.test;
public class ThreadUtil {
private static ThreadLocal<News> threadLocal = new ThreadLocal<News>();
public static ThreadLocal<News> getThreadLocal() {
return threadLocal;
}
}
範例:修改TestMessage的內容
package org.lks.test;
public class TestMessage {
public static void main(String[] args) {
News vo = new News();
vo.setTitle("hhy big fool");
Message msg = new Message();
ThreadUtil.getThreadLocal().set(vo);
msg.print();
}
}
此時沒有必要再去處理引用關係,而直接利用ThreadLocal完成。
一般如果要在實際開發之中使用的話,往往用於數據庫連接處理類的操作上。
2 HibernateSessionFactory分析
在MyEclipse裏面爲了簡化開發提供有這樣的工具類,這個工具類的主要目的是取得SessionFactory以及Session對象。現在最爲重要的實際上是Session對象,所有的數據操作由此展開。
範例:分析HibernateSessionFactory
package org.lks.dbc;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
//表示提供有ThreadLocal對象保存,適合於進行線程的準確處理
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; //連接工廠
private static Configuration configuration = new Configuration(); //讀取配置文件
private static ServiceRegistry serviceRegistry; //服務註冊類
static { //靜態代碼塊,可以在類加載的時候執行一次
try {
configuration.configure(); //讀取配置文件
serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
try {
//在靜態塊中就已經準備好了SessionFactory類的對象
sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() { //構造方法私有化,因爲本類不需要提供構造
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* 取得Session對象,對象是通過ThreadLocal類取得的,如果沒有保存的Session,那麼會重新連接
*
* @return Session操作對象
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
//爲了防止用戶可能重複使用Session對象,是通過保存在ThreadLocal類中的Session直接使用的
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) { //如果第一次使用或者之前關閉了,那麼Session爲null
if (sessionFactory == null) { //判斷此時是否存在有SessionFactory類對象
rebuildSessionFactory(); //如果SessionFactory不存在,則重新創建一個SessionFactory
}
//判斷此時是否取得了SessionFactory類對象,如果取得,則使用openSession()打開新Session,否則返回null
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session); //爲了防止可能重複使用Session,將其保存在ThreadLocal中。
}
return session;
}
/**
* Rebuild hibernate session factory
*
* 重新進行SessionFactory類對象的創建
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* 所有操作的最後一定要關閉Session,在業務層中關閉
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get(); //取得已有的Session對象
threadLocal.set(null); //清空ThreadLocal的保存
if (session != null) { //將Session進行關閉
session.close();
}
}
/**
* return session factory
*
* 取得SessionFactory類的對象,目的是爲了進行緩存操作
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
* 取得Configuration類的對象
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
這個類只要使用就可以取得Session、SessionFactory、Configuration類的對象,至於如何取的,可以暫時不關心(因爲Hibernate不可能單獨使用,單獨使用沒有優勢,都會結合到Spring上使用)。
範例:使用這個連接工廠類
package org.lks.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.lks.dbc.HibernateSessionFactory;
import org.lks.pojo.Member;
public class TestMemberInsertDemoSimple {
public static void main(String[] args) throws ParseException {
// 1、設置VO的屬性內容的操作應該由控制層完成
Member pojo = new Member();
pojo.setMid("31613012201");
pojo.setMname("lks");
pojo.setMage(23);
pojo.setMsalary(2000.0);
pojo.setMnote("hhy big fool!");
pojo.setMbirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1996-10-15"));
// 2、數據的保存操作應該由數據層完成
HibernateSessionFactory.getSession().save(pojo);
// 3、事務以及Session的關閉應該由業務層完成
HibernateSessionFactory.getSession().beginTransaction().commit();
HibernateSessionFactory.closeSession();
}
}
以後在講解Hibernate過程之中,就是用如上的操作方式。