1. 程式人生 > >02-建立Hibernate工程

02-建立Hibernate工程

Hibernate工程主要步驟

  • 建立Hibernate的配置檔案
  • 建立持久化類
  • 建立物件-關係對映檔案
  • 通過Hibernate API編寫訪問資料庫的程式碼

建立專案

  1. 開啟IntelliJ IDEA 選擇Java應用,勾選Web Application & Hibernate
    在這裡插入圖片描述

    填寫專案名之後,等待jar包的下載專案建立成功後如下圖所示

    在這裡插入圖片描述

建立Hibernate的配置檔案

  1. 建立Hibernate的配置檔案

    在第一步建立專案的時候可以勾選 create default hibernate configuration and main class,如果沒有勾選的話可以進到Project Structure -> Module -> Hibernate 面板下進行手動建立配置,然後切記選擇路徑到src下,點選OK。
    在這裡插入圖片描述

    在這裡插入圖片描述

進行hibernate.cfg.xml檔案的配置

這裡本地資料庫使用mysql,首先匯入mysql-connector-java-8.0.12.jar這個jar包然後進行session-factory標籤中字標籤的配置

	    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/BookDB?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">*****</property>

        <!-- 設定方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <mapping resource="/com/example/BooksEntity.hbm.xml"/>

    </session-factory>
	```
	- connection.url是連線的資料庫的地址
	- connection.driver_class 連線資料庫的驅動
	- connection.username 資料庫的使用者名稱
	- connection.password 資料庫的密碼
	- hibernate.dialect 方言,語法格式
	- hibernate.show_sql 
	- hibernate.format_sql
	- hibernate.hbm2ddl.auto 

配置資料庫並建立實體化類及關係對映檔案

我本地是mysql資料庫,在Intellij IDEA配置連線資料庫.

在這裡插入圖片描述
在這裡插入圖片描述

實體類的建立可以根據資料庫手動建立在Intellij IDEA中也可以自動建立。

在Persistence面板中右鍵選擇 Generate Persistence Mapping -> By Database Schema,即可自動生成實體化類物件和對應的關係對映檔案。如下圖所示

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

這裡生成的關係對映檔案,就是hibernate 配置檔案 hibernate.cfg.xmlmapping標籤對應的值

依賴Junit通過Hibernate API編寫訪問資料庫的程式碼進行單元測試

三個標籤
@Test: 測試方法
@Before: 初始化方法
@After: 釋放資源
執行順序會先執行 @Before標籤對應的方法,然後執行@Test標籤對應的方法,最後執行@After標籤對應的方法。

  1. 新增junit依賴

    在這裡插入圖片描述

  2. 建立測試類

    在這裡插入圖片描述

  3. 執行測試方法

    在這裡插入圖片描述

  4. 正確執行後,會顯示一個綠條的進度條,同時資料庫中也會有儲存的資料

    在這裡插入圖片描述

    在這裡插入圖片描述


在這裡插入圖片描述