三大架構之hibernate入門,三大hibernate入門
hibernate入門 1、orm hibernate是一個經典的開源的orm[資料訪問中介軟體]架構 ORM( Object Relation Mapping)對象關係映射 通過 物件模型 操作 資料庫關聯式模式hibernate處於項目的持久層位置,因此又稱為持久層架構 2、hibernate核心組件 SessionFactory [整個資料庫的操作] 重量級組件 Session[對資料庫的一次業務操作] -- 輕量級組件 3、hibernate配置 配置SessionFactory 4、使用hibernate開發一個APP 在導好jar包後: a.配置hibernate.cfg.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!--Database connection settings --> 8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>10 <property name="connection.username">scott</property>11 <property name="connection.password">tiger</property>12 <!--SQL dialect 方言-->13 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>14 <!--Enable Hibernate's automatic session context management -->15 <property name="current_session_context_class">thread</property>16 <!--Echo all executed SQL to stdout -->17 <property name="show_sql">true</property>18 <mapping resource="com/it/bean/UserInfo.hbm.xml"/>19 </session-factory>20 </hibernate-configuration>
SessionFactory --- 關聯 xxx.hbm.xmlUserInfo.hbm.xml的配置: 1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping package="com.it.bean"> 6 <class name="UserInfo" table="userinfo"> 7 <id name="user_id" column="user_id"> 8 <!-- 主鍵建置原則 --> 9 <generator class="assigned"></generator>10 </id>11 <property name="user_name" column="user_name"></property>12 <property name="user_sex" column="user_sex"></property>13 <property name="user_birth" column="user_birth"></property>14 <property name="user_addr" column="user_addr"></property>15 <property name="user_pwd" column="user_pwd"></property> 16 </class>17 </hibernate-mapping>View Code
補充:
主鍵建置原則:
-
Assigned:主鍵由外部程式產生,無需Hibernate幹預。
-
identity:採用資料庫提供的主鍵產生機制,如MySql、DB2、SqlServer的自增主鍵。
-
sequence:使用資料庫的sequence機制。
-
hilo:通過hi/lo 演算法實現的主鍵產生機制,需要額外的資料庫表儲存主鍵產生曆史狀態。
-
seqhilo:與hilo 類似,通過hi/lo 演算法實現的主鍵產生機制,只是主鍵曆史狀態儲存在Sequence中,適用於支援Sequence的資料庫,如Oracle。
-
increment:主鍵按數值順序遞增。此方式的實現機製為在當前應用執行個體中維持一個變數,以儲存著當前的最大值,之後每次需要產生主鍵的時候將此值加1作為主鍵。這種方式可能產生的問題是:如果當前有多個執行個體訪問同一個資料庫,那麼由於各個執行個體各自維護主鍵狀態,不同執行個體可能產生同樣的主鍵,從而造成主鍵重複異常。因此,如果同一資料庫有多個執行個體訪問,此方式必須避免使用。
-
native:由Hibernate根據底層資料庫定義自行判斷採用identity、hilo、sequence其中一種作為主鍵產生方式。
-
foreign:使用外部表格的欄位作為主鍵。
-
uuid.hex:由Hibernate基於128 位唯一值產生演算法,根據IP、目前時間、JVM啟動時間、內部自增量產生16 進位數值(編碼後以長度32 的字串表示)作為主鍵,該方法提供了最好的資料庫插入效能和資料庫平台適應性。
- uuid.string:與uuid.hex 類似,只是產生的主鍵未進行編碼(長度16),在某些資料庫中可能出現問題(如PostgreSQL)。
b、建立sessionFactorySessionFactory
sessionFactory=(SessionFactory)
new Configuration().configure().buildSessionFactory(); c.建立SessionSession session=sessionFactory .getCurrentSession(); d.建立Transaction//建立事務並開啟事務Transaction tx = session.beginTransaction(); e.開啟事務 f.執行操作--業務操作 g.提交事務tx.commit(); h.異常處理塊,交易回復在try catch異常處理後,tx.rollback;完整代碼(basedao): 1 package com.it.dao; 2 import java.util.List; 3 import org.hibernate.Query; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.Transaction; 6 import org.hibernate.cfg.Configuration; 7 import org.hibernate.classic.Session; 8 import com.it.dao.util.SessionFactoryUtils; 9 /** 10 * 基礎DAO 11 * @author xj 12 * 13 */ 14 public class BaseDAO <T>{ 15 /** 16 * 查詢集合--全部 17 */ 18 public List<T> find(String hql){ 19 Session session =null; 20 //事務 21 Transaction tx = null; 22 List<T> list =null; 23 try { 24 //這裡將建立SessionFactory寫成了方法(工具類)--建立SessionFactory並得到Session 25 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 26 //開啟事務 27 tx=session.beginTransaction(); 28 //查詢Java bean UserInfo--對象這裡hql是查詢語句:eg:from UserInfo(UserInfo-->是java bean裡的對象) 29 Query query = session.createQuery(hql); 30 list = query.list(); 31 //提交 32 tx.commit(); 33 } catch (Exception e) { 34 e.printStackTrace(); 35 //交易回復 36 tx.rollback(); 37 } 38 return list; 39 } 40 41 /** 42 * 查詢帶參數 43 */ 44 public List<T> find(String hql,String ...params){ 45 Session session =null; 46 //事務 47 Transaction tx = null; 48 List<T> list =null; 49 try { 50 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 51 //開啟事務 52 tx=session.beginTransaction(); 53 //查詢Java bean UserInfo--對象 54 Query query = session.createQuery(hql); 55 //給參數賦值 56 for (int i = 0; i < params.length; i++) { 57 query.setString(i, params[i]); 58 } 59 list = query.list(); 60 //提交 61 tx.commit(); 62 } catch (Exception e) { 63 e.printStackTrace(); 64 //交易回復 65 tx.rollback(); 66 } 67 return list; 68 } 69 70 } 71 /** 72 * 添加 73 * @param obj 74 */ 75 public void add(Object obj){ 76 Session session =null; 77 Transaction tx = null; 78 try { 79 // 80 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 81 tx=session.beginTransaction(); 82 //操作 83 session.save(obj); 84 //提交 85 tx.commit(); 86 } catch (Exception e) { 87 // TODO: handle exception 88 e.printStackTrace(); 89 //交易回復 90 tx.rollback(); 91 System.out.println("--我復原啦---"); 92 } 93 } 94 95 /** 96 * 按對象刪除 97 */ 98 public void del(Object obj){ 99 Session session =null;100 Transaction tx = null;101 try {102 //103 session=SessionFactoryUtils.getSessionFactory().getCurrentSession();104 tx=session.beginTransaction();105 //操作106 session.delete(obj);107 //提交108 tx.commit();109 } catch (Exception e) {110 // TODO: handle exception111 e.printStackTrace();112 //交易回復113 tx.rollback();114 System.out.println("--我復原啦---");115 }116 }117 /**118 * 按編號刪除119 */120 public void delete(Class<T> clz, String OID){121 Session session =null;122 Transaction tx = null;123 //通過給的id來查詢該id的對象124 Object o=get(clz,OID);125 try {126 //127 session=SessionFactoryUtils.getSessionFactory().getCurrentSession();128 tx=session.beginTransaction();129 //操作130 session.delete(o);131 //提交132 tx.commit();133 } catch (Exception e) {134 // TODO: handle exception135 e.printStackTrace();136 //交易回復137 tx.rollback();138 System.out.println("--我復原啦---");139 }140 }141 142 /**143 * 修改144 * @param obj145 */146 public void upd(Object obj){147 Session session =null;148 Transaction tx = null;149 try {150 //得到SessionFactory151 session=SessionFactoryUtils.getSessionFactory().getCurrentSession();152 //開啟事務153 tx=session.beginTransaction();154 //操作155 session.update(obj);156 //提交157 tx.commit();158 } catch (Exception e) {159 // TODO: handle exception160 e.printStackTrace();161 //交易回復162 tx.rollback();163 System.out.println("--我復原啦---");164 }165 }166 167 /**168 * 查詢169 */170 public T get(Class<T> clz, String OID){171 Session session =null;172 Transaction tx = null;173 T t=null;174 try {175 //176 session=SessionFactoryUtils.getSessionFactory().getCurrentSession();177 tx=session.beginTransaction();178 //操作179 t = (T) session.get(getClass(), OID);180 //提交181 tx.commit();182 } catch (Exception e) {183 // TODO: handle exception184 e.printStackTrace();185 //交易回復186 tx.rollback();187 System.out.println("--我復原啦---");188 }189 return t;190 }191 View Code
hibernate導的包: