Hibernate總結(一)

一、hibernate總體知識架構圖

本文主要是按照這幅圖來組織知識點


二、知識準備

1.hibernate使用的場景

只能說hibernate不適應的場景來說:

1.不適合OLAP(On-Line Analytical Processing聯機分析處理),以查詢分析數據爲主的系統;適合OLTP(On-line transaction processing 聯機事務處理)。
2.對於些關係模型設計不合理的老系統,也不能發揮hibernate優勢。
3.數據量巨大,性能要求苛刻的系統,hibernate也很難達到要求,批量操作數據的效率也不高。

總之:hibernate對數據的查詢效率較低

給程序員提供的一些便利是以消耗性能來提供的。


2.hibernate常用API(五大核心接口)


具體方法

Configuration配置對象,對應着配置文件
configure(String)
configure() 加載默認的主配置文件(hibernate.cfg.xml)
addResource(String)
addClass(Class)
buildSessionFactory()
方法鏈


SessionFactory Session工廠
openSession() 打開一個新的Session
getCurrentSession()
close()


Session
beginTransaction()
getTransaction()
close() 關閉
----------
save(Object)
update(Object)
delete(Object)刪除的是實體對象
get(Class, id) : Object
createQuery(String hql) : Query
...

Query
list() : List
uniqueResult() : Object
setFirstResult(int)
setMaxResults(int)


Criteria(不算是核心類)

一種查詢方法

Criteria.add(Restrictions.eq("name", name))

Transaction
begin()
commit()
rollbacl()


3.如何搭建hibernate;

1)導入jar包

2)在src下建立hibernate.cfg.xml文件

3)創建實體類

4)建立實體類對應的XXX .hbm.xml;

5)將XXX .hbm.xml;註冊到hibernate.cfg.xml


6)創建HibernateUtil

代碼如下:

	private static SessionFactory sessionFactory = null ;
	//靜態初始化快(在類加載時創建)
	static {
		try{
			//Configuration表示hibernate初始器
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}catch(Throwable e){
			System.out.println("hibernate 初始化失敗!");
			e.printStackTrace();
			//throw new ExceptionInInitializerError(e);
		}
	}
	/**
	 * 得到SessionFactory
	 * @return
	 */
	public static SessionFactory getSeesionFactoty()
	{
		return sessionFactory;
	}
	/**
	 * 得到Session
	 * @return
	 */
	public static Session getSession()
	{
		return sessionFactory.openSession();//一個作用就是擁有事務
	}


4.持久化對象的三種狀態

分別爲:瞬時狀態(Transient),持久化狀態(Persistent),離線狀態(Detached)。三種狀態下的對象的生命週期如下


  三種狀態的區別是:

瞬時狀態的對象:沒有被session管理,在數據庫沒有;

離線狀態:沒有被session管理,但是在數據庫中存在。

持久化狀態的對象:被session管理,在數據庫存在,當屬性發生改變,在清理緩存時,會自動和數據庫同步;(注意,改變會同步)


hibernate訪問持久化對象(如下圖):



















發佈了34 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章