1. 程式人生 > >Hibernate單表對映配置

Hibernate單表對映配置

在上一篇部落格中已經配置好了Hibernate的開發環境,今天直接基於上一篇的開發環境操作。ibernate 是一個開放原始碼的 ORM 框架,它對 JDBC 進行了輕量級的物件封裝,使得 Java 開發人員可以使用面向物件的程式設計思想來操作資料庫

建立資料庫和實體類

持久化類是應用程式中的業務實體類,這裡的持久化是指類的物件能夠被持久化儲存到資料庫中。Hibernate 使用普通 Java 物件(Plain Old Java Object),即 POJO 的程式設計模式來進行持久化。POJO類中包含的是與資料庫表相對應的各個屬性,這些屬性通過 getter 和 setter 方法來訪問,對外部隱藏了內部的實現細節。下面就來編寫 Customer 持久化類。

在專案 src 目錄下,建立 com.gaowei.entity 包,並在包中建立實體類 Customer(對應資料庫表tab_customer),Customer 類包含與 table_customer 資料表字段對應的屬性,以及相應的 getXxx ()和setXxx ()方法。

/*建立客戶表*/
CREATE TABLE `tab_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_address` varchar(128) DEFAULT NULL COMMENT '客戶聯絡地址',
`cust_phone` varchar(64) DEFAULT NULL COMMENT '客戶聯絡電話',
PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
package com.gaowei.entity;

import java.io.Serializable;

/**
 * 客戶實體類
 * @author gaoweiFu
 *	
 */
public class Customer implements Serializable {
	private Long custId; //編號
	private String cudtName;//姓名
	private String custSource;//來源
	private String custIndustry;//行業
	private String custLevel;//級別
	private String custAddress;//地址
	private String custPhone;//手機號碼
	public Long getCustId() {
		return custId;
	}
	public void setCustId(Long custId) {
		this.custId = custId;
	}
	public String getCudtName() {
		return cudtName;
	}
	public void setCudtName(String cudtName) {
		this.cudtName = cudtName;
	}
	public String getCustSource() {
		return custSource;
	}
	public void setCustSource(String custSource) {
		this.custSource = custSource;
	}
	public String getCustIndustry() {
		return custIndustry;
	}
	public void setCustIndustry(String custIndustry) {
		this.custIndustry = custIndustry;
	}
	public String getCustLevel() {
		return custLevel;
	}
	public void setCustLevel(String custLevel) {
		this.custLevel = custLevel;
	}
	public String getCustAddress() {
		return custAddress;
	}
	public void setCustAddress(String custAddress) {
		this.custAddress = custAddress;
	}
	public String getCustPhone() {
		return custPhone;
	}
	public void setCustPhone(String custPhone) {
		this.custPhone = custPhone;
	}
	@Override
	public String toString() {
		return "Customer [custId=" + custId + ", cudtName=" + cudtName + ", custSource=" + custSource
				+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
				+ ", custPhone=" + custPhone + "]";
	}
	
}

編寫對映檔案(*.hbm.xml)

實體類Customer 目前還不具備持久化操作的能力,而 Hibernate 需要知道實體類 Customer 對映到資料庫 Hibernate 中的哪個表,以及類中的哪個屬性對應資料庫表中的哪個欄位,這些都需要在對映檔案中配置。在實體類Customer所在的包中,建立一個名稱為Customer.hbm.xml的對映檔案,在該檔案中定義了實體類 Customer 的屬性是如何對映到 tab_customer 表的列上的。
<?xml version="1.0" encoding="UTF-8"?>
<!-- 匯入約束:dtd約束
	位置:在 Hibernate 的核心 jar 包中名稱為 hibernate-mapping-3.0.dtd
	Hibernate-core-5.0.7Final.jar下的org.hibernate下的hibernate-mapping-3.0.dtd檔案中
	明確該檔案中的內容:
			1:實體類和表的對應關係
			2:實體類中屬性和表的欄位的對應關係
 -->
 <!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:指定實體類的名稱,全限定類名
			table:指定資料庫表的名稱
     -->
    	<class name="com.gaowei.entity.Customer" table="tab_customer">
    	        <!-- id 標籤
				作用:用於對映主鍵
				屬性:
				name:指定的是屬性名稱。也就是 get/set 方法後面的部分,並且首字母要轉小寫。
				column:指定的是資料庫表的欄位名稱
		-->
    		<id name="custId" column="cust_id">
    			<!-- generator 標籤:
						作用:配置主鍵的生成策略。
						屬性:
						class:指定生成方式的取值。
						取值之一:native。使用本地資料庫的自動增長能力。
						mysql 資料庫的自動增長能力是讓某一列自動+1。但是不是所有資料庫都支援這種方
						式。
			-->
    			<generator class="native"></generator>
    		</id>
    		<!-- property 標籤:
				作用:對映其他欄位
				屬性:
				name:指定屬性的名稱。和 id 標籤的 name 屬性含義一致
				column:指定資料庫表的欄位名稱
		-->
                <property name="custName" column="cust_name"></property>
		<property name="custLevel" column="cust_level"></property>
		<property name="custSource" column="cust_source"></property>
		<property name="custIndustry" column="cust_industry"></property>
		<property name="custAddress" column="cust_address"></property>
		<property name="custPhone" column="cust_phone"></property>
    	</class>
    
    </hibernate-mapping>

編寫Hibernate主配置檔案

Hibernate 的對映檔案反映了持久化類和資料庫表的對映資訊,而 Hibernate 的配置檔案則主要用來配置資料庫連線以及 Hibernate 執行時所需要的各個屬性的值。在專案的 src 下建立一個名稱為hibernate.cfg.xml 的檔案.

?xml version="1.0" encoding="UTF-8"?>
<!-- 匯入約束:去核心包中找:/org/hibernate/hibernate-configuration-3.0.dtd  -->
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- 
	使用者建立SessionFactory的 ,這個session工廠就是為了建立Session的
	
	1、連結資料庫的資訊
	2、Hibernate的基本配置資訊
	3、對映檔案的位置
	
	這三部分資訊都能在這個檔案中找到:xxx\hibernate-release-5.0.7.Final\project\etc\hibernate.properties
	這個檔案:是key和value的結構,只是用的是空格分隔
	-->
	<session-factory>
		<!-- 1、資料庫的連結資訊 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_day01</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">passw0rd</property>
		<!-- 方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<!-- 2、Hibernate的基本配置 -->
		<!-- 顯示sql語句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 格式化sql語句 -->
		<property name="hibernate.format_sql">true</property>
		<!-- 配置Hibernate的DDL語句:讓hibernate幫我們自動維護表結構:
				只需要知道update就可以了,其他的可以看講義
				有表就維護表
				沒有表就建立表
		 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 3、對映檔案的位置 -->
		<mapping resource="com/gaowei/entity/Customer.hbm.xml"/>
		
		
	</session-factory>
</hibernate-configuration>

測試

在專案中新建一個名稱為 com.gaowei.test 的包,然後在包中建立一個名為 HibernateDemo1.java 的檔案,該檔案是用來測試的類檔案。

/**
* hibernate 的入門案例:
* 需求:把一個客戶儲存到資料庫中
* @author gaoweiFu
*
*/

public class HibernateDemo1 {
/**
* 步驟分析:
* 1、載入主配置檔案
* 2、根據主配置檔案中的配置構建 SessionFactory
* 3、使用工廠生產一個 Session 物件
* 4、使用 Session 物件開啟事務
* 5、執行儲存客戶操作
* 6、提交事務
* 7、釋放資源
*/
    @Test
    public void test1(){
        Customer c = new Customer();
        c.setCustName("純情電腦公司");
        //1.載入主配置檔案
        Configuration cfg = new Configuration();
        cfg.configure();
        //2.構建 SessionFactory
        SessionFactory factory = cfg.buildSessionFactory();
        //3.使用 SessionFactory 生產一個 Session
        Session session = factory.openSession();//開啟一個新的 Session
        //4.開啟事務
        Transaction tx = session.beginTransaction();
        //5.儲存客戶
        session.save(c);//根據對映配置檔案,生成 SQL 語句,實現儲存。
        //6.提交事務
        tx.commit();
        //7.釋放資源
        session.close();
        factory.close();
    }
}

Hibernate執行流程

首先建立 Configuration 類的例項,並通過它來讀取並解析配置檔案 hibernate.cfg.xml。然後建立SessionFactory 讀取解析對映檔案資訊,並將 Configuration 物件中的所有配置資訊拷貝到SessionFactory 記憶體中。接下來,開啟 Session,讓 SessionFactory 提供連線,並開啟一個事務,之後建立物件,向物件中新增資料,通過 session.save()方法完成向資料庫中儲存資料的操作。最後提交事務,並關閉資源。