hibernate框架的學習--第一天


一.   hibernate是什么

 1.   框架是什么

      1).框架是用來提高開發效率的

      2).封裝了好了一些功能.我們需要使用這些功能時,調用即可.不需要再手動實現.

      3).所以框架可以理解成是一個半成品的項目.只要懂得如何駕馭這些功能即可.

    2.  hibernate框架是什么

     

    3.   hibernate的好處

        1)   操作數據庫的時候,可以以面向對象的方式來完成.不需要書寫SQL語句

    4.  hibernate是一款orm框架

           orm:object relationg mapping. 對象關系映射

              

 

      1)   orm分4級

         hibernate屬於4級:完全面向對象操作數據庫

         mybatis屬於2級

         dbutils屬於1級

二.   hibernate框架的搭建

     1.導包

       1)Jar包

    

       2).   驅動包

     

      2. 創建數據庫,准備表,實體 

      1)數據庫表

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)',
  `cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',
  `cust_user_id` bigint(32) DEFAULT NULL COMMENT '負責人id',
  `cust_create_id` bigint(32) DEFAULT NULL COMMENT '創建人id',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客戶信息來源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級別',
  `cust_linkman` varchar(64) DEFAULT NULL COMMENT '聯系人',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定電話',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移動電話',
  PRIMARY KEY (`cust_id`)
)

 2)實體

/**
 * 客戶實體類
 * @author vanguard
 *
 */
public class Customer {
    
    private Long cust_id;
    private String cust_name;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_linkman;
    private String cust_phone;
    private String cust_mobile;
    public Long getCust_id() {
        return cust_id;
    }
    public void setCust_id(Long cust_id) {
        this.cust_id = cust_id;
    }
    public String getCust_name() {
        return cust_name;
    }
    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }
    public String getCust_source() {
        return cust_source;
    }
    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }
    public String getCust_industry() {
        return cust_industry;
    }
    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }
    public String getCust_level() {
        return cust_level;
    }
    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }
    public String getCust_linkman() {
        return cust_linkman;
    }
    public void setCust_linkman(String cust_linkman) {
        this.cust_linkman = cust_linkman;
    }
    public String getCust_phone() {
        return cust_phone;
    }
    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }
    public String getCust_mobile() {
        return cust_mobile;
    }
    public void setCust_mobile(String cust_mobile) {
        this.cust_mobile = cust_mobile;
    }
    
    @Override
    public String toString() {
        return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name
                + "]";
    }
    
}

 

    3.  書寫orm元數據(對象與表的映射配置文件)

  1)導入約束

       2)

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

       3)ORM元數據

      

    4   書寫主配置文件

     

     

    

    5.書寫代碼測試

/**
 * hibernate快速入門
 * 使用hibernate操作客戶表b
 * @author vanguard
 *
 */
public class Demo {
    @Test
    public void fun() {
        //1. 創建Configuration對象並加載主配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 根據配置文件,創建SessionFactory對象
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 獲得session對象
        Session session = sf.openSession();
        
        //4. 開啟事務
        Transaction tx = session.beginTransaction();
        /********************************/
        Customer c = new Customer();
        c.setCust_name("google");
        //執行保存
        session.save(c);
        
        /********************************/
        // 提交事務
        tx.commit();
        //釋放資源
        session.close();
        sf.close();
    }
}    

三   配置文件詳解

     1    orm元數據

       

 1 <?xml version="1.0" encoding="UTF-8"?>
 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     
 6 <!-- 配置表與實體對象的關系 -->
 7 <!-- package屬性:填寫一個包名,在元素內部凡是需要完整的類名的屬性,直接寫簡化的類名 -->
 8 <hibernate-mapping package="com.java.domain">
 9 
10     <!-- 
11         class元素:配置實體與表的對應關系
12         name:完整類名
13         table:數據庫表名
14      -->
15     <class name="Customer" table="cst_customer">
16     
17         <!-- 
18             id元素:配置主鍵映射的屬性
19             name:填寫主鍵對應的屬性名
20             column(可選):填寫表中的主鍵列名.默認值:主鍵會默認使用屬性名
21             type(可選):填寫列(屬性)的類型。hibernate會自動檢測實體的屬性類型
22                         每個類型有三種填法:java類型|hibernate類型|數據庫類型
23             not-null(可選):配置該屬性(列)是否不能為空。默認值:false
24             length(可選):配置數據庫中列的長度。默認值:使用數據庫類型的最大長度
25          -->
26         <id name="cust_id" column="cust_id">
27             <!-- 主鍵生成策略(7個)
28                  identity:主鍵自增,有數據庫維護主鍵值,錄入時不需要指定主鍵
29                  sequence:Oracle中的主鍵生成策略,
30                  increment(了解):主鍵自增,由hibernate來維護,每次插入前會先查詢表中id最大值,+1作為新主鍵
31                  hilo(了解):高低位算法,主鍵自增,由hibernate維護,開發時不使用
32                  native:hile+sequence+identity 自動三選一策略
33                  uuid:產生隨機字符串作為主鍵,主鍵必須是string類型
34                  assigned:自然主鍵生成策略,hibernate不會管理主鍵值,由開發人員錄入
35              -->
36             <generator class="native"></generator>
37         </id>
38         
39         <!-- 
40             property元素:除id之外的普通屬性的映射
41             name:填寫屬性名
42             column(可選):填寫列名 默認值:會默認使用屬性名
43             type(可選):填寫列(屬性)的類型。hibernate會自動檢測實體的屬性類型
44                         每個類型有三種填法:java類型|hibernate類型|數據庫類型
45             not-null(可選):配置該屬性(列)是否不能為空。默認值:false
46             length(可選):配置數據庫中列的長度。默認值:使用數據庫類型的最大長度
47          -->
48         <property name="cust_name" column="cust_name">
49             <!-- <column name="cust_name" sql-type="varchar"></column> -->
50         </property>    
51         <property name="cust_source" column="cust_source"></property>
52         <property name="cust_industry" column="cust_industry"></property>
53         <property name="cust_level" column="cust_level"></property>
54         <property name="cust_linkman" column="cust_linkman"></property>
55         <property name="cust_phone" column="cust_phone"></property>
56         <property name="cust_mobile" column="cust_mobile"></property>
57     </class>
58 </hibernate-mapping>

  2  hibernate主配置 

          1)  必選屬性配置(5個)

        

<!-- 必選屬性配置(5個) -->
        
        <!-- 數據庫驅動 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 數據庫url -->
        <property name="hibernate.connection.url">jdbc:mysql:///crm</property>
        <!-- 數據庫連接用戶名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 數據庫連接密碼 -->
        <property name="hibernate.connection.password">root</property>
        <!-- 
            數據庫方言:
            不同數據庫中,sql語法略有區別,指定方言可以讓hibernate框架再生成sql語句時,針對數據庫的方言生成
            sql99標准: DDL:數據定義語言 庫表的增刪改查
                       DCL:數據控制語言 事務 權限
                       DML:數據操縱語言 增刪改查
            注意:mysql在選擇方言時,選擇最短的方言 org.hibernate.dialect.MySQLDialect              
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    

            

         2)    可選屬性配置(3個)

       

<!-- 可選的配置(3個) -->
        <!-- 
        #hibernate.show_sql true
        #hibernate.format_sql true     
        -->
        <!-- 將hibernate生成的sql語句打印在控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 將hibernate生成sql語句格式化(縮進) -->
        <property name="hibernate.format_sql">true</property>
        <!--     
        ## auto schema export 自動導出表結構  自動建表
        #hibernate.hbm2ddl.auto create 自動建表,每次運行框架都會創建新的表,以前的表會被覆蓋,數據會丟失(開發環境測試使用)
        #hibernate.hbm2ddl.auto create-drop 自動建表,每次運行框架運行結束都會刪除所用表(測試環境中使用)
        #hibernate.hbm2ddl.auto update(推薦使用) 自動生成表,如果已經存在不會再生成,如果表有變動,自動更新表(不會刪除任何數據)
        #hibernate.hbm2ddl.auto validate 校驗:不自動建表,每次啟動會校驗數據庫中的表是否正確,不正確則校驗失敗,拋出異常
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>

  3) 元數據引入配置

         

        <!-- 
            引入orm數據源
            路徑填寫:src下的路徑
         --> 
        <mapping resource="com/java/domain/Customer_hbm.xml"/>

四、hibernateAPI詳解

 1   Configuration

       

/**
     * Configuration
     */
    @Test
    public void fun1() {
        //1. 創建configuration對象,調用空參構造
        Configuration configure = new Configuration();
        
        //2. 讀取配置文件
        Configuration conf = configure.configure();
        
        //3. 讀取指定的orm元數據(擴展),如果主配置中已經引入映射配置文件不需要手動加載
//        conf.addResource(resourceName);
//        conf.addClass(persistentClass);
        
        //4. 根據配置文件,創建SessionFactory
        SessionFactory sessionFactory = conf.buildSessionFactory();
        
        sessionFactory.close();
    }   

    2    SessionFactory 

      SessionFactory對象
      功能:用於創建數據庫核心對象session對象的工廠。簡單說就是創建session對象。
      注意:1. sessionFactory用於保存和使用所有配置信息,消耗內存資源非常大
               2. sessionFactory屬於線程安全的對象
     結論:保證WEB應項目中,只創建一個sessionFactory
/**
     * SessionFactory對象
     * 功能:用於創建數據庫核心對象session對象的工廠。簡單說就是創建session對象。
     * 注意:1. sessionFactory用於保存和使用所有配置信息,消耗內存資源非常大
     *          2. sessionFactory屬於線程安全的對象
     * 結論:保證WEB應項目中,只創建一個sessionFactory
     * 
     */
    @Test
    public void fun2() {
        //1. 創建configuration對象,並讀取配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 根據配置文件,創建SessionFactory
        SessionFactory sessionFactory = conf.buildSessionFactory();
        
        //3. 打開一個新的session對象
        Session session = sessionFactory.openSession();
        //獲得與線程綁定的esssion對象
        Session session2 = sessionFactory.getCurrentSession();
        
        sessionFactory.close();
    }

      3    Session 

  Session對象
  功能:表示hibernate框架與數據庫之前的連接(會話),sesssion類似於
  JDBC的connection對象,還可以完成對數據庫的增刪改查操作,
  session是hibernate操作數據庫的核心對象

     

/**
     * Session對象
     * 功能:表示hibernate框架與數據庫之前的連接(會話),sesssion類似於
     *          JDBC的connection對象,還可以完成對數據庫的增刪改查操作,
     *          session是hibernate操作數據庫的核心對象
     */
    @Test
    public void fun3() {
        //1. 創建Configuration對象,並加載配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 建立sessionfactory工廠對象
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打開一個新的session對象
        Session session = sf.openSession();
        
        //4. 獲得事務
        Transaction tx = session.getTransaction();
        
        //5. 開啟事務
        tx.begin();
        
        
    }

 

         1) session對數據庫進行增加操作 

   /**
     * session對數據庫進行增加的操作
     */
    @Test
    public void fun1() {
        //1. 創建Configuration對象,並加載配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 建立sessionfactory工廠對象
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打開一個新的session對象
        Session session = sf.openSession();
        
        //4. 開啟事務並獲得操作事務的對象
        Transaction tx = session.beginTransaction();
        /*********操作數據庫********************/
        
        Customer c = new Customer();
        c.setCust_name("百度");
        session.save(c);
        
        /**************************************/
        //提交事務
        tx.commit();
        //釋放資源
        session.close();
        sf.close();
        
    }

         2)session對數據進行查詢操作

          

/**
     * 對數據庫進行查詢操作
     */
    @Test
    public void fun2() {
        //1. 創建configuraion對象並加載配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 創建sessionfactory工廠
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打開一個新的session對象
        Session session = sf.openSession();
        
        //4. 開啟事務並獲得操作事務的對象
        Transaction tx = session.beginTransaction();
        
        //5. 對數據庫進行刪除操作
        //獲得需要修改的對象
        Customer customer = session.get(Customer.class, 2l);
        System.out.println(customer);
        //6. 提交事務
        tx.commit();
        
        //7. 釋放資源
        session.close();
        sf.close();
    }

        3)session對數據庫進行刪除操作

         

/**
     * session對數據庫進行刪除操作
     */
    @Test
    public void fun3() {
        //1. 創建configuraion對象並加載配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 創建sessionfactory工廠
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打開一個新的session對象
        Session session = sf.openSession();
        
        //4. 開啟事務並獲得操作事務的對象
        Transaction tx = session.beginTransaction();
        
        //5. 對數據庫進行刪除操作
        //獲得需要刪除的對象
        Customer customer = session.get(Customer.class, 1l);
        //執行刪除操作
        session.delete(customer);
        
        //6. 提交事務
        tx.commit();
        
        //7. 釋放資源
        session.close();
        sf.close();
    }

          4)session對數據庫進行修改操作

         

/**
     * 對數據庫進行修改操作
     */
    @Test
    public void fun4() {
        //1. 創建configuraion對象並加載配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 創建sessionfactory工廠
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打開一個新的session對象
        Session session = sf.openSession();
        
        //4. 開啟事務並獲得操作事務的對象
        Transaction tx = session.beginTransaction();
        
        //5. 對數據庫進行刪除操作
        //獲得需要修改的對象
        Customer customer = session.get(Customer.class, 2l);
        customer.setCust_name("騰訊");
        //執行修改操作
        session.update(customer);
        
        //6. 提交事務
        tx.commit();
        
        //7. 釋放資源
        session.close();
        sf.close();
    }

       4. Tracsaction

          hibernate內部封裝了事務的操作,只需要調用方法即可

          1)打開事務

         方式一:

    //1. 獲得事務
        Transaction tx = session.getTransaction();
        //2. 開啟事務
        tx.begin();

 

         方式二(推薦):

      // 開啟事務並獲得操作事務的對象
        Transaction tx = session.beginTransaction();

          2)提交事務

            tx.commit();

          3)回滾事務

           tx.rollback();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM