1. 程式人生 > >Hibernate(1)Hibernate簡介和簡單示例,瞭解Hibernate事務回滾用法

Hibernate(1)Hibernate簡介和簡單示例,瞭解Hibernate事務回滾用法

1 Hibernate簡介

  • Hibernate是一個orm(object relation mapping 物件關係對映)框架,處於專案的持久層,也叫持久層框架(持久層框架還有ojb等)。
  • Hibernate本質就是對JDBC進行了輕量級的封裝。

2 使用Hibernate的好處

①引入Hibernate可以使工作人員角色細化,讓程式設計師更關心業務流程。讓資料庫人員更關注資料庫相關的各種操作。
②分層更加清晰,耦合性更小
③通用性強:可以更輕鬆地從一個數據庫平臺轉移到別的平臺
④物件化:把關係資料庫程式設計Java物件,更加方便操作
⑤效能保證:Hibernate可能按不同的資料庫,處理不同的操作是用最優化的SQL語句,不用我們去想,對於分等演算法,在Hibernate中會顯得更簡單,可靠。
⑥增加了程式的魯棒性

3 一些概念和開發方式

①介紹:Hibernate開發的三種方式:
- 由Domain Object->mapping->db。(官方推薦)
- 由DB開始,用工具生成mapping和Domain Object。(使用較多)
- 由對映檔案開始。
②資料持久層/物件關係對映檔案【該檔案會說明表和物件的關係,以及物件的屬性和表的欄位的對應關係;命名規範Domain物件名.hbm.xml

4 簡單示例

①引入Hibernate開發包(http://pan.baidu.com/s/1qYwe6ny
②建立資料表,編寫Domain程式碼
③編寫Employee.hbm.xml

檔案(物件關係對映檔案)

<?xml version="1.0" encoding="utf-8" ?>
<!-- 對映檔案需要一個dtd來指定格式 -->
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.test.domain">
    <class
name="Employee" table="employee">
<!-- id元素用於指定主鍵屬性 --> <id name="id" column="id" type="java.lang.Integer"> <!-- 該元素用於指定主鍵值生成策略(共7種, sequence等) --> <generator class="sequence"> <param name="sequence">employee_seq</param> </generator> </id> <!-- 對其他屬性的配置 --> <property name="name" type="java.lang.String"> <column name="name" not-null="false"></column> </property> <property name="email" type="java.lang.String"> <column name="email" not-null="false"></column> </property> <property name="hiredate" type="java.util.Date"> <column name="hiredate" not-null="false"></column> </property> </class> </hibernate-mapping>

④手動配置hibernate.cfg.xml檔案(Hibernate的核心配置檔案),該檔案用於配置連線的資料庫的型別,driver,使用者名稱,密碼等(hibernate-distribution-3.3.1.GA-dist\hibernate-distribution-3.3.1.GA\project\etc)

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- hibernate設計者,給我提供了一些常用配置 -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.username">scott</property>
        <property name="connection.password">tiger</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <!-- 配置dialect方言,明確告訴Hibernate使用哪種資料庫 -->
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- 管理設定的對映檔案 -->
        <mapping resource="com/test/domain/Employee.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

⑤編寫testMain.java檔案,測試crud

public static void deleteEmployee() {
    Session session = MySessionFactory.getSessionfactory().openSession();

    Transaction ts = session.beginTransaction();

    session.delete(session.load(Employee.class, 3));

    ts.commit();

    session.close();
}

public static void updateEmployee() {
    Session session = MySessionFactory.getSessionfactory().openSession();

    Transaction ts = session.beginTransaction();

    // 修改使用者
    Employee employee = (Employee) session.load(Employee.class, 3);

    employee.setName("你好啊");
    ts.commit();

    session.close();
}

public static void addEmployee() {
    // 1 建立Configuration,該物件用於讀取hibernate.cfg.xml檔案,並完成初始化
//      Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
    Configuration configuration = new Configuration().configure(); // 預設是hibernate.cfg.xml
    // 2 建立SessionFactory【這是一個會話工廠,是一個重量級的物件】
    SessionFactory sessionfactory = configuration.buildSessionFactory();
    // 3 建立session,相當於jdbc connection【】
    Session session = sessionfactory.openSession();
    // 4 對Hibernate來說,要求在進行CRUD操作時,使用事務提交       
    Transaction transcation = session.beginTransaction();

    // 新增一個僱員
    Employee employee = new Employee();
    employee.setName("jiaozenglian");
    employee.setEmail("[email protected]");
    employee.setHiredate(new Date());

    // 儲存
    session.save(employee); // ==> insert into ...
    // 提交
    transcation.commit();
    session.close();
}

MySessionFactory.java檔案(由於配置物件比較耗費資源,故將其設定為單例)

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public final class MySessionFactory {
    private static SessionFactory sessionfactory = null;
    static {
        sessionfactory = new Configuration().configure().buildSessionFactory();
    }

    public static SessionFactory getSessionfactory() {
        return sessionfactory;
    }
}

5 切換資料庫

①首先,重新配置hibernate.cfg.xml檔案

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- hibernate設計者,給我提供了一些常用配置 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">111111</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <!-- 配置dialect方言,明確告訴Hibernate使用哪種資料庫 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 顯示出對應的sql語句 -->
        <property name="show_sql">true</property>
        <!-- 讓Hibernate自動給我們建立表       create:表示建立該表   update:表示如果沒有該表才建立 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 管理設定的對映檔案 -->
        <mapping resource="com/test/domain/Employee.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

②配置Employee.hbm.xml檔案

<?xml version="1.0" encoding="utf-8" ?>
<!-- 對映檔案需要一個dtd來指定格式 -->
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.test.domain">
    <class name="Employee" table="employee">
        <!-- id元素用於指定主鍵屬性 -->
        <!--<id name="id" column="id" type="java.lang.Integer">
             該元素用於指定主鍵值生成策略(共7種, sequence等) 
            <generator class="sequence">
                <param name="sequence">employee_seq</param>
            </generator>
        </id> -->
        <!-- 這裡針對MySQL主鍵自動增長方式,進行配置 -->
        <id name="id" column="id" type="java.lang.Integer">
            <generator class="increment"></generator>
        </id>
        <!-- 如果使用者希望自己設定id,使用assigned
        <id name="id" column="id" type="java.lang.Integer">
            <generator class="assigned"/>
        </id>   -->
        <!-- 對其他屬性的配置 ------------以下可以不變 -->
        <property name="name" type="java.lang.String">
            <column name="name" length="64" not-null="false"></column>
        </property>
        <property name="email" type="java.lang.String">
            <column name="email" not-null="false"></column>
        </property>
        <property name="hiredate" type="java.util.Date">
            <column name="hiredate" not-null="false"></column>
        </property>
    </class>
</hibernate-mapping>

6 Hibernate基本原理圖

這裡寫圖片描述
只有Configuration是一個類class,其他三個都是介面interface。
- Hibernate需要的其他庫
這裡寫圖片描述

7 優化updateEmployee新增事務回滾

public static void updateEmployee() {
    // 回滾事務
    Session session = MySessionFactory.getSessionfactory().openSession();

    Transaction ts = null;
    try {
        ts = session.beginTransaction();
        // 修改使用者
        Employee employee = (Employee) session.load(Employee.class, 3);

        employee.setName("nihao");

        ts.commit();

    } catch (Exception e) {
        if(ts!=null) {
            ts.rollback();
        }
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    } finally {
        if(session!=null && session.isOpen()) {
            session.close();
        }
    }
}