看視訊學hibernate(一)
hibernate模板程式碼
Session session = hibernateUtils.openSession(); Transaction tx =null; try { tx = session.beginTransaction(); session.save(user); tx.commit(); } catch (RuntimeException e) { System.out.println("錯誤原因: "+e.getMessage()); tx.rollback(); throw e; }finally{ session.close(); }
JDBC 模板程式碼
開啟資料庫
註冊驅動
獲取連線
得到語句
……..
關閉連線
API
1.簡介
2.Session中的方法
3.查詢HQL與Criteria
配置
1.主配置檔案
2.對映檔案
普通屬性
主鍵
集合屬性
關聯關係
1-N
N-1
1-1
N-N
繼承結構
Configuration
configure(); 讀取預設檔案
configure(Strig resource); 讀取指定檔案
buildSessionFactory
addResource(String resource) 匯入一個指定位置的對映檔案
addClass(class className) 匯入與指定類同一個包中的以類名為字首,字尾為.hbm.xml的對映檔案
SessionTactory
openSession();
getCurretSession();
close();
Session
操作物件的方法
save(Object)
update(Object)
delete(Object)
查詢的方法
createQuery(String)
createCriteria(Class)
管理事務的方法
beginTransaction();——Transaction(返回一個事物物件)
getTransaction() —得到與當前session關聯的事務
其他方法——-
Transaction
comnint();
rollback();
Query
list(); 得到一個集合結果
uniqueResult() 得到一個唯一的結果,如果沒有結果,返回 NULL
如果結果又多個,就丟擲異常
hibernate主配置檔案
1.配置的key前面的hibernate. 字首可有可無,如 hibernate.dialect 或dialect
2.按作用可分為三類
1.資料庫資訊
方言,URL,驅動,使用者名稱,密碼
2.匯入對映檔案
3.其他配置
show_sql
format_sql
hbm2ddl.auto 自動生成表結構
....
對映檔案的作用:配置 物件與表的關係
物件 ——對映配置——–表
生成表結構的2種方式
1.hbm2ddl.auto
2.使用 SchemaExport 工具類
總結
hibernate
持久層框架
新增環境
1.jar包
2.配置檔案
hibernate.cg.xml
xxx.hbm.xml
3.
使用hibernate實現增刪查改(CRUD)
準備
Configuration cfg = new Configuration.configure();
SesstionFactory sesstionFactory = cfg.buildSesstionFactory();//只需要一個
模板程式碼
Session session = sesstionFactory .openSession();
Transaction tx =null;
try {
tx = session.beginTransaction();
//session.save(user);//操作
tx.commit();
} catch (RuntimeException e) {
System.out.println("錯誤原因: "+e.getMessage());
tx.rollback();
throw e;
}finally{
session.close();
}
操作 Session中的方法
save(Object)
update(Object)
delete(Object)
get(class,id)
createQuery(hql)
saveOrUpdate(Object)
…..
以上根據方言生成不同資料庫的SQL語句
主配置檔案
1.資料庫資訊
方言 URL 驅動 使用者名稱 密碼
2.其他資訊
show_sql
format…
hbm2ddl.auto
…
3.匯入對映檔案
對映配置
對映基礎
類–表
屬性—列
對映普通屬性
name type column length not-null …
對映主鍵
主鍵生成策略:native(主鍵是數字型別) uuid(hibernate自動指定,但是主鍵是必須是字串型別)
mysql–identy
orcal–
SQL-server–