[Java] Hibernate 使用 .hbm.xml 配置

Hibernate 安裝好之後,若用對應檔案 .hbm.xml 的作法如下:

檔案配置

  1. 在 src / main / java 右鍵 New > Other... 搜尋 hibernate,選擇 Hibernate Configuration File (cfg.xml),點 Next 使用預設的檔名 hibernate.cfg.xml 即可(若更動檔名則後續在使用時, .configure() 要另外指定檔名)
  2. 可用他的 Wizard 來輸入完成 cfg.xml ,或直接 Finish ,在檔案右鍵 Open With > Generic Text Editor 手動輸入
  3. 如果 MySQL 的 database 叫 mydb,帳號 root,密碼 abc1234,則 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.cj.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">abc1234</property>
    
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
            <property name="hbm2ddl.auto">update</property>
    		
            <mapping resource="db/Obj.hbm.xml" />
        </session-factory>
    </hibernate-configuration>

    • show_sql 是 console 是否顯示 SQL 指令
    • format_sql 是前者是否排版
    • mapping resource 放的是持久化物件與關聯式資料庫表格之對應檔案位置,若物件是 package db 裡的 class Obj,則檔案為 db/Obj.hbm.xml ,要注意映射文件資料夾路徑是用「 / 」而不是「 . 」

  4. 在欲映射的持久化物件的同資料夾要有同名的對應檔案 hbm.xml,例如 package db 之下的 class Obj,就要在 db/ 下有 Obj.hbm.xml ,可以手動新增文字檔,或在 Project Explorer 下面樹狀圖於 Obj 資料夾右鍵 New > Other... ,選 Hibernate XML Mapping file (hbm.xml) > Next > Next > 選好資料夾,設定好檔名 > Finish ,一樣如果不使用 XML Editor ,可在樹狀圖中找到 hbm.xml 右鍵 Open with > Generic Text Editor 來編輯。Obj.hbm.xml 範例如下:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    	
    <hibernate-mapping>
        <class name="db.Obj" table="mytable">
            <id name="varId" column="id" type="java.lang.Integer">
                <generator class="increment"></generator>
            </id>
            <property name="var2" type="java.lang.String" update="true" insert="true" column="col2" not-null="false"/>
            <property name="var3" type="java.lang.Integer" update="true" insert="true" column="col3" not-null="false"/>
        </class>
    </hibernate-mapping>
        

    持久化物件 Obj 與資料庫中的表格 mytable 互相對應。每個<property>在定義對映,name="物件變數" 而 column="表格欄位名"。例如物件變數 Integer varId 與資料庫中表格 id 對應;物件變數 String var2 與表格 col2 對應;物件變數 Integer var3 與表格 col3 對應,就如上的配置。<id>標籤是對應表格的主鍵 primary key 是 id 與物件的 varId,而<generator> 標籤是 Hibernate insert 進 SQL 時主鍵生成方式採用遞增 increment,還有 assigned 、native 可使用。

使用 Hibernate

  1. 有幾個步驟,用 cfg.xml 做 Configuration().configure()、建立 SessionFactory、開啓 Session
  2. 在要使用 Hibernate 的 class 例如 TestIO:
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import java.util.List;
    
    public class TestIO {
    
        private static SessionFactory factory;
    	
        public static void main(String[] args) {
            factory = new Configuration()
                    .configure()
                    .buildSessionFactory();
            // 若 hibernate.cfg.xml 檔名不在根目錄或檔名有換,路徑要寫在 .configure()之中
            // 例如 .configure("/dir/hibernate2.cfg.xml")
            
            Session session = factory.openSession();
            // 由 SessionFactory 開啓工作階段
          
            Transaction transaction = session.beginTransaction();
            // 由session開始事務
    
    
    
    
            // 開始始用 Hibernate 做 CRUD
    
    
    
    
            transaction.commit();   // 提交事務,將上述該存入的存入、該讀出的讀出
            factory.close();       // 關閉SessionFactory
            session.close();       // 關閉session
        }
    }
    

和使用 Annotation 的差別

  • 持久化物件旁要有 .hbm.xml 檔案,而且 hibernate.cfg.xml 之中必須要有 <mapping> 標籤
  • 類別中不用寫 @ 等註解,且使用時 Configuration() 不用.addAnnotatedClass(Obj.class)

使用 Hibernate 來做 CRUD 請見連結

留言