一、Hibernate-入門

1、概述

一、什麼是Hibernate:

Hibernate是一個開放源代碼的對象關係映射框架,它對JDBC進行了很是輕量級的對象封裝,它將POJO與數據庫表創建映射關係,是一個全自動的orm框架,hibernate能夠自動生成SQL語句,自動執行,使得Java程序員能夠爲所欲爲的使用對象編程思惟來操縱數據庫。 Hibernate能夠應用在任何使用JDBC的場合,既能夠在Java的客戶端程序使用,也能夠在Servlet/JSP的Web應用中使用,最具革命意義的是,Hibernate能夠在應用EJB的JaveEE架構中取代CMP,完成數據持久化的重任。java

 

二、什麼是ORM:

ORM:Object Relational Mapping(對象關係映射)。指的是將一個Java中的對象與關係型數據庫中的表創建一種映射關係,從而操做對象就能夠操做數據庫中的表。mysql

 

三、Hibernate的做用:

一、對象化。程序員

hibernate可讓開發人員以面相對象的思想來操做數據庫。jdbc只能經過SQL語句將元數據傳送給數據庫,進行數據操做。而hibernate能夠在底層對元數據和對象進行轉化,使得開發者只用面向對象的方式來存取數據便可。sql

二、更好的移植性。數據庫

hibernate使用xml或JPA的配置以及數據庫方言等等的機制,使得hibernate具備更好的移植性,對於不一樣的數據庫,開發者只須要使用相同的數據操做便可,無需關心數據庫之間的差別。而直接使用JDBC就不得不考慮數據庫差別的問題。編程

三、開發效率高。緩存

hibernate提供了大量的封裝(這也是它最大的缺點),不少數據操做以及關聯關係等都被封裝的很好,開發者不需寫大量的sql語句,這就極大的提升了開發者的開發效率。安全

四、緩存機制的使用。session

hibernate提供了緩存機制(session緩存,二級緩存,查詢緩存),對於那些改動不大且常用的數據,能夠將它們放到緩存中,沒必要在每次使用時都去查詢數據庫,緩存機制對提高性能大有裨益。架構

                                                                   

 

 

 

 2、建立項目

一、下載的hibernate目錄:

                  

documentation           :Hibernate開發的文檔

lib                               :Hibernate開發包

 required                    :Hibernate開發的必須的依賴包

 optional                    :Hibernate開發的可選的jar包

  project                     :Hibernate提供的項目

二、建立一個基礎的Java項目,導入對應的Jar便可。

                    

 

 

 

三、建立表

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)',
  `cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客戶信息來源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級別',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定電話',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移動電話',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 

 

四、建立對應的實體類

package com.turtle.dao;

import java.io.Serializable;

public class Customer implements Serializable {

    // 客戶編號(主鍵)
    private Long cust_id;
    // 客戶名稱(公司名稱)
    private String cust_name;
    // 客戶信息來源
    private String cust_source;
    // 客戶所屬行業
    private String cust_industry;
    // 客戶級別
    private String cust_level;
    // 固定電話
    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_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;
    }
}

 

 

五、建立映射

映射須要經過XML的配置文件來完成,這個配置文件能夠任意命名。儘可能統一命名規範(類名.hbm.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- 創建類與表的映射 -->
    <class name="com.turtle.dao.Customer" table="cst_customer">
        <!-- 創建類中的屬性與表中的主鍵對應 -->
        <id name="cust_id" column="cust_id" >
            <generator class="native"/>
        </id>

        <!-- 創建類中的普通的屬性和表的字段的對應 -->
        <property name="cust_name" column="cust_name" length="32" />
        <property name="cust_source" column="cust_source" length="32"/>
        <property name="cust_industry" column="cust_industry"/>
        <property name="cust_level" column="cust_level"/>
        <property name="cust_phone" column="cust_phone"/>
        <property name="cust_mobile" column="cust_mobile"/>
    </class>
</hibernate-mapping>

 

【class標籤的配置】

  標籤用來創建類與表的映射關係

  屬性:

  name                :類的全路徑

  table                 :表名(類名與表名一致,table能夠省略)

  catalog             :數據庫名

 

【id標籤的配置】

  標籤用來創建類中的屬性與表中的主鍵的對應關係

  屬性:

  name                :類中的屬性名

  column             :表中的字段名(類中的屬性名和表中的字段名若是一致,column能夠省略)

  length               :長度

  type                   :類型

 

【property標籤的配置】

  標籤用來創建類中的普通屬性與表的字段的對應關係

  屬性:

  name                :類中的屬性名

  column             :表中的字段名

  length               :長度

  type                   :類型

  not-null            :設置非空

  unique              :設置惟一

 

六、建立一個Hibernate的核心配置文件

Hibernate的核心配置文件的名稱:hibernate.cfg.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 鏈接數據庫的基本參數 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate_demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!-- 配置Hibernate的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- 可選配置================ -->
        <!-- 打印SQL -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL -->
        <property name="hibernate.format_sql">true</property>
        <!-- 自動建立表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 配置C3P0鏈接池 -->
        <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
        <!--在鏈接池中可用的數據庫鏈接的最少數目 -->
        <property name="c3p0.min_size">5</property>
        <!--在鏈接池中全部數據庫鏈接的最大數目  -->
        <property name="c3p0.max_size">20</property>
        <!--設定數據庫鏈接的過時時間,以秒爲單位,
        若是鏈接池中的某個數據庫鏈接處於空閒狀態的時間超過了timeout時間,就會從鏈接池中清除 -->
        <property name="c3p0.timeout">120</property>
        <!--每3000秒檢查全部鏈接池中的空閒鏈接 以秒爲單位-->
        <property name="c3p0.idle_test_period">3000</property>

        <mapping resource="com/turtle/dao/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 

  必須的配置

    鏈接數據庫的基本的參數

    驅動類

    url路徑

    用戶名

    密碼

    方言

 可選的配置

   顯示SQL          :hibernate.show_sql

    格式化SQL     :hibernate.format_sql

    自動建表        :hibernate.hbm2ddl.auto

      none                 :不使用hibernate的自動建表

      create               :若是數據庫中已經有表,刪除原有表,從新建立,若是沒有表,新建表。(測試)

      create-drop     :若是數據庫中已經有表,刪除原有表,執行操做,刪除這個表。若是沒有表,新建一個,使用完了刪除該表。(測試)

      update             :若是數據庫中有表,使用原有表,若是沒有表,建立新表(更新表結構)

     validate            :若是沒有表,不會建立表。只會使用數據庫中原有的表。(校驗映射和表結構)。

 映射文件的引入    

    引入映射文件的位置

  <mapping resource="com/turtle/dao/Customer.hbm.xml"/>

 

七、編寫測試代碼

package com.turtle.test;

import com.turtle.dao.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class TestCustomer {
    public static  void main(String [] args){
        // 一、加載配置文件
        Configuration configuration = new Configuration().configure();
        // 二、建立一個SessionFactory對象
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 三、建立Session對象
        Session session = sessionFactory.openSession();
        // 四、開啓事務
        Transaction transaction = session.beginTransaction();
        try{
            Customer customer = new Customer();
            customer.setCust_name("測試用戶1");
            // 調用Hibernate自帶的API來進行保存操做
            session.save(customer);
            // 提交事務
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            // 回滾事務
            transaction.rollback();
        }finally {
            // 關閉鏈接
            session.close();
        }
    }
}

 

 八、控制檯打印的SQL語句和數據的結果表數據

                                                                          

 

                                                                          

3、Hibernate的API

一、Configuration:Hibernate的配置對象

  做用:加載核心配置文件

 

hibernate.properties

Configuration cfg = new Configuration();

 

 hibernate.cfg.xml

Configuration cfg = new Configuration().configure();

  加載映射文件

 

// 手動加載映射

configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml");

 

二、 SessionFactory:Session工廠

SessionFactory內部維護了Hibernate的鏈接池和Hibernate的二級緩存(不講)。是線程安全的對象。一個項目建立一個對象便可。

 

三、Session:相似Connection對象是鏈接對象

Session表明的是Hibernate與數據庫的連接對象。不是線程安全的。與數據庫交互橋樑。

  Session中的API

  保存方法:

    Serializable save(Object obj);

  查詢方法:

    T get(Class c,Serializable id);

    T load(Class c,Serializable id);

  修改方法

   void update(Object obj);

  刪除方法

    void delete(Object obj);s

  保存或更新

    void saveOrUpdate(Object obj)

 

四、  Transaction:事務對象

Hibernate中管理事務的對象。

    commit();

    rollback();

相關文章
相關標籤/搜索