Hibernate(1)框架介紹及準備工作

目錄

Hibernate入門

1.下載Hibernate

2.創建實體類和數據庫

3.創建映射文件

4.創建hibernate核心配置文件

測試:

Hibernate幫助類


 

Hibernate與mybatis框架一樣都是dao層持久層框架之一,Hibernate是一個開放源代碼的ORM(object /relational mapping對象關係映射),它對JDBC進行了輕量級的封裝,使得java開發人員可以使用面向對象的編程思想來操作數據庫。

Hibernate入門

1.下載Hibernate

下載地址https://sourceforge.net/projects/hibernate/

解壓完後

documentation 存放了hibernate相關文檔,包括參考文檔的api文檔

lib文件夾存放了hibernate編譯和運行的相關jar包,其中required子文件夾下包含了hibernate5項目必須的jar包

project存放了hibernate各種相關的源代碼。

在lib/required下的jar包,需要在hibernate項目中引入。

數據庫驅動包

以及

日誌相關的包

2.創建實體類和數據庫

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_linkman` VARCHAR(64) 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 cn.ycsj.domain;

public class Customer {
	private Long cust_id;
	
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_linkman;
	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_linkman() {
		return cust_linkman;
	}
	public void setCust_linkman(String cust_linkman) {
		this.cust_linkman = cust_linkman;
	}
	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;
	}
	@Override
	public String toString() {
		return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + "]";
	}
}

3.創建映射文件

實體類目前目前還不具備持久化操作的能力,而hibernate需要直到實體類custormer映射到數據庫Hibernate中的哪個表,以及類中的哪個屬性對應數據庫表中的哪個字段,這些都需要在映射文件中配置,在實體類custormer類所在的包中,創建一個名爲custormer.hbm.xml的映射文件,該文件中定義了實體類custormer的屬性是如何映射到cst_custormer表的列上的。

<?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">
   <!-- 配置表與實體對象的關係 -->
   <!-- package屬性:填寫一個包名.在元素內部凡是需要書寫完整類名的屬性,可以直接寫簡答類名了. -->
<hibernate-mapping package="cn.ycsj.domain" >
	<!-- 
		class元素: 配置實體與表的對應關係的
			name: 完整類名
			table:數據庫表名
	 -->
	<class name="Customer" table="cst_customer" >
		<!-- id元素:配置主鍵映射的屬性
				name: 填寫主鍵對應屬性名
				column(可選): 填寫表中的主鍵列名.默認值:列名會默認使用屬性名
				type(可選):填寫列(屬性)的類型.hibernate會自動檢測實體的屬性類型.
						每個類型有三種填法: java類型|hibernate類型|數據庫類型
				not-null(可選):配置該屬性(列)是否不能爲空. 默認值:false
				length(可選):配置數據庫中列的長度. 默認值:使用數據庫類型的最大長度
		 -->
		<id name="cust_id"  >
			<!-- generator:主鍵生成策略(明天講) -->
			<generator class="native"></generator>
		</id>
		<!-- property元素:除id之外的普通屬性映射
				name: 填寫屬性名
				column(可選): 填寫列名
				type(可選):填寫列(屬性)的類型.hibernate會自動檢測實體的屬性類型.
						每個類型有三種填法: java類型|hibernate類型|數據庫類型
				not-null(可選):配置該屬性(列)是否不能爲空. 默認值:false
				length(可選):配置數據庫中列的長度. 默認值:使用數據庫類型的最大長度
		 -->
		<property name="cust_name" column="cust_name" >
			<!--  <column name="cust_name" sql-type="varchar" ></column> -->
		</property>
		<property name="cust_source" column="cust_source" ></property>
		<property name="cust_industry" column="cust_industry" ></property>
		<property name="cust_level" column="cust_level" ></property>
		<property name="cust_linkman" column="cust_linkman" ></property>
		<property name="cust_phone" column="cust_phone" ></property>
		<property name="cust_mobile" column="cust_mobile" ></property>
	</class>
</hibernate-mapping>

4.創建hibernate核心配置文件

hibernate的映射文件反映了持久化類和數據庫表的映射關係,而hibernate的配置文件則主要用來配置數據庫連接和hibernate運行時鎖需要的各個屬性的值,在項目的src目錄下牀架一個名爲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>

        <!--
        #hibernate.dialect org.hibernate.dialect.MySQLDialect
        #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
        #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
        #hibernate.connection.driver_class com.mysql.jdbc.Driver
        #hibernate.connection.url jdbc:mysql:///test
        #hibernate.connection.username gavin
        #hibernate.connection.password
         -->
        <!-- 數據庫驅動 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 數據庫url -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost/hib</property>
        <!-- 數據庫連接用戶名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 數據庫連接密碼 -->
        <property name="hibernate.connection.password">123456</property>
        <!-- 數據庫方言
            不同的數據庫中,sql語法略有區別. 指定方言可以讓hibernate框架在生成sql語句時.針對數據庫的方言生成.
            sql99標準: DDL 定義語言  庫表的增刪改查
                      DCL 控制語言  事務 權限
                      DML 操縱語言  增刪改查
            注意: MYSQL在選擇方言時,請選擇最短的方言.
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>


        <!-- #hibernate.show_sql true
             #hibernate.format_sql true
        -->
        <!-- 將hibernate生成的sql語句打印到控制檯 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 將hibernate生成的sql語句格式化(語法縮進) -->
        <property name="hibernate.format_sql">true</property>
        <!--
        ## auto schema export  自動導出表結構. 自動建表
        #hibernate.hbm2ddl.auto create		自動建表.每次框架運行都會創建新的表.以前表將會被覆蓋,表數據會丟失.(開發環境中測試使用)
        #hibernate.hbm2ddl.auto create-drop 自動建表.每次框架運行結束都會將所有表刪除.(開發環境中測試使用)
        #hibernate.hbm2ddl.auto update(推薦使用) 自動生成表.如果已經存在不會再生成.如果表有變動.自動更新表(不會刪除任何數據).
        #hibernate.hbm2ddl.auto validate	校驗.不自動生成表.每次啓動會校驗數據庫中表是否正確.校驗失敗.
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 引入orm元數據
            路徑書寫: 填寫src下的路徑
         -->
        <mapping resource="cn/ycsj/domain/Customer.hbm.xml" />

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

測試:

    public void test1(){
        //1.創建使用空參構造,空參加載方法是加載src下的hibernate.cfg.xml文件
        Configuration conf = new Configuration().configure();

        //2.讀取元數據文件(映射文件),如果主配置文件中已經加入映射盤配置,則不需要手動加入
        //conf.addResource(reaourceName);
        //conf.addClass(persistantClass);

        //3.根據配置信息,創建sessionfactroy
        SessionFactory sessionFactory = conf.buildSessionFactory();

        //4.獲得session
        //打開一個新的session對象
        Session session = sessionFactory.openSession();
        //獲取一個與線程綁定的session    
        // Session session = sessionFactory.getCurrentSessio();
        
        Transaction transaction = session.beginTransaction();
        //------數據庫操作
        Customer c = new Customer();
        c.setCust_name("好啊好啊");
        session.save(c);  //執行保存


        //~~~~~~~~~~~~~~~~~~~
        transaction.commit();
        session.close();
        sessionFactory.close();

    }

HibernateAPI

Configuration  加載配置文件

SessionFactory對象,用來創建操作數據庫核心對象session對象的工廠,簡單來說功能只有一個 創建session對象。

注意: 1sessionfactory用來保存和使用所有配置信息,消耗內存資源非常大。

         2.sessionfactory屬於線程安全的對象設計

結論,保證在項目中,只創建一個sessionfactory 

session對象

//session hibernate框架與數據庫之間的連接(會話)
//與JDBC年代的connection 類似 更加先進  可以完成對數據庫的增刪改查
//session是hibernate操作數據庫的核心對象。
//session獲得操作事務的transaction對象
//獲得操作事務的對象
//Transaction tx = session.getTransaction();
//獲得並開啓操作事務的對象(推薦使用)
Transaction transaction = session.beginTransaction();
//------數據庫操作

//~~~~~~~~~~~~~~~~~~~
transaction.commit();//提交事務
//transaction.rollback();//回滾
session.close();
sessionFactory.close();

查詢根據id查詢 id爲主鍵

    public void test3(){
        Configuration conf = new Configuration().configure();
        SessionFactory sessionFactory = conf.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Transaction transaction = session.beginTransaction();
        //------數據庫操作
        Customer customer = session.get(Customer.class, 1l);
        System.out.println(customer);

        //~~~~~~~~~~~~~~~~~~~
        transaction.commit();//提交事務
        session.close();
        sessionFactory.close();

    }

修改數據

 public void test4(){
        Configuration conf = new Configuration().configure();
        SessionFactory sessionFactory = conf.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Transaction transaction = session.beginTransaction();
        //------數據庫操作
        Customer customer = session.get(Customer.class, 1l);
        customer.setCust_mobile("12345");
        session.update(customer);

        //~~~~~~~~~~~~~~~~~~~
        transaction.commit();//提交事務
        session.close();
        sessionFactory.close();
}

刪除數據

 @Test
    public void test5(){
        Configuration conf = new Configuration().configure();
        SessionFactory sessionFactory = conf.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Transaction transaction = session.beginTransaction();
        //------數據庫操作
        Customer customer = session.get(Customer.class, 2l);

        session.delete(customer);

        //~~~~~~~~~~~~~~~~~~~
        transaction.commit();//提交事務
        session.close();
        sessionFactory.close();

    }

Hibernate幫助類

package cn.ycsj.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibetnateUtils {

    private static SessionFactory sessionFactory;
    static {
        Configuration conf = new Configuration().configure();
         sessionFactory = conf.buildSessionFactory();
    }

    //獲得全新的session
    public  static Session openSession(){
        return sessionFactory.openSession();

    }

    //獲得與線程綁定的session
    public  static  Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

}

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章