1.Hibernate入門

前言:JAVA EE 開發的架構
三層架構
在這裏插入圖片描述
層與框架之間的關係
在這裏插入圖片描述
說明:使用Servlet、JSP+JavaBean+JDBC這套架構可以開發市面上的所有應用,但是因爲其過於底層,在企業中不會使用。企業中開發一般使用SSH(Struts+Spring+Hibernate)和SSM(SpringMVC+Spring+Mybatis)。

什麼是Hibernate?
Hibernate是持久層的ORM的框架。

ORM概述:對象關係映射(Object Relational Mapping),指的是將一個Java中的類與關係型數據庫中的表建立一種映射關係,從而操作對象就可以操作數據庫中的表。在這裏插入圖片描述
爲什麼要學習Hibernate?
在這裏插入圖片描述

:Hibernate可以在Java項目中使用,也可以在Web項目中使用,接下來以Java項目爲例。

1.Hibernate入門
解壓Hibernate:
在這裏插入圖片描述
documentation:Hibernate開發的文檔;
lib:Hibernate開發包;
  lib\required:Hibernate開發的必須的依賴包;
  lib\optional:Hibernate開發的可選的依賴包;
project:Hibernate提供的項目。

創建項目,導入.jar包:
數據庫驅動包
mysql-connector-java-5.1.7-bin.jar
Hibernate開發的必須的jar包
D:\hibernate-release-5.0.7.Final\lib\required 目錄下的所有jar包
Hibernate引入日誌記錄包
log4j-1.2.16.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.7.2.jar

執行操作:全選引入的jar包,右鍵選擇build path;

創建表:可以先創建一個數據庫,然後再在數據庫裏建表

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_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;

創建客戶管理的類:
此處省略生成的get、set方法

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_phone;
    private String cust_mobile;
    //此處省略對應的get、set方法
    
}

創建配置文件:
映射配置文件:創建在於映射類同一個包下,儘量統一命名規範爲:類名.hbm.xml

<?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">
    
<hibernate-mapping>
    <!-- 建立類與表的映射 -->
    <class name = "hibernate_start.Customer" table = "cst_customer">
        <!-- 建立類中的屬性與表中的主鍵對應 -->
        <id name = "cust_id" column = "cust_id">
            <generator class="native"/>
        </id>
        
        <!-- 建立類中的普通的屬性和表的字段的對應 -->
        <property name="cust_name" column = "cust_name"/>
        <property name="cust_source" column = "cust_source"/>
        <property name="cust_industry" column = "cust_industry"/>
        <property name="cust_level" column = "cust_level"/>
        <property name="cust_phone" column = "cust_phone"/>
        <property name="cust_mobile" column = "cust_mobile"/>
    </class>
</hibernate-mapping>

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>
        <!-- 連接數據庫的基本參數 -->
        <property name = "hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property>
        <property name = "hibernate.connection.url" >jdbc:mysql:///hibernate_start</property>
        <property name = "hibernate.connection.username" >root</property>
        <property name = "hibernate.connection.password" >2e5y8hxf</property>
        
        <!-- hibernate方言設置 -->
        <property name = "hibernate.dialect" >org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 可選配置 -->
        <!-- 打印SQL -->
        <!-- 格式化SQL -->
        <property name = "hibernate.show_sql">true</property>
        <property name = "hibernate.format_sql">true</property>
        
        <mapping resource = "hibernate_start/Customer.hbm.xml"/>
    </session-factory>    
</hibernate-configuration>

Hibernate測試類編寫:

public class HibernateDemo1 {
    @Test
    public void demo1() {
    	//1.加載Hibernate的核心配置文件
    	Configuration configuration = new Configuration().configure();
    	//2.創建一個SessionFactory對象:類似於JDBC中的連接池
    	SessionFactory sessionFactory = configuration.buildSessionFactory();
    	//3.通過SessionFactory獲取到Session對象:類似於JDBC中的Connection
    	Session session = sessionFactory.openSession();
    	//4.手動開啓事務
    	Transaction transaction = session.beginTransaction();
    	//5.編寫代碼
    	Customer customer = new Customer();
    	customer.setCust_name("張三");
    	session.save(customer);
    	//6.事務提交
    	transaction.commit();
    	//7.資源釋放
    	session.close();
    }
}

測試結果:cust_name爲“張三”的數據被添加進來了,
在這裏插入圖片描述

2.Hibernate中XML文件常用配置
提示配置:
在eclipse中找到Window/Preferences
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
映射配置文件:
class標籤的配置:該標籤用來建立類與表的映射關係
屬性
  name:類的全路徑
  table:表名(若類名與表名一致,table可以省略)
  catalog:數據庫名(可以省略)
在這裏插入圖片描述
id標籤的配置:該標籤用來建立類中的屬性與表中的主鍵的對應關係
屬性
  name:類中的屬性名
  column:表中的字段名(類中的屬性名與表中的字段名如果一致,column可以省略)
  length:長度
  type:類型
在這裏插入圖片描述
property標籤的配置:該標籤用來建立類中的普通屬性與表中字段的對應關係
屬性
  name:類中的屬性名
  column:表中的字段名
  length:長度
  type:類型
  not-null:設置非空
  unique:設置唯一
在這裏插入圖片描述
核心配置文件:
Hibernate核心配置方式:
方式一:屬性文件的方式,hibernate.properties
舉例:hibernate.connection.driver_class=com.mysql.jdbc.Driver
   …
   hibernate.show_sql=true
注:屬性配置的方式不能引入映射文件(需要手動編寫代碼加載映射文件)
方式二:XML文件的方式
hibernate.cfg.xml
核心配置:
必須的配置
連接數據庫的基本參數:
  驅動類
  url路徑
  用戶名
  密碼
  在這裏插入圖片描述
方言:
在這裏插入圖片描述
可選的配置
顯示SQL:hibernate.show_sql
在這裏插入圖片描述
格式化SQL:hibernate.format_sql
在這裏插入圖片描述
自動建表:hibernate.hbm2ddl.auto
  none:不使用hibernate中的自動建表
  create:如果數據庫中已經有表,刪除原有表,重寫創建,如果沒有表,新建表。(一般用於測試)
  create-drop:如果數據庫中已經有表,刪除原有表,執行相應操作,之後再刪除這個表;如果沒有表,則新建一個表,使用完之後刪除表。(一般用於測試)
  update:如果數據庫中有表,使用原有表;如果沒有表,則創建新表(更新表結構)。
  validate:如果數據庫中沒有表,也不會創建表,只會使用數據庫中原有的表(這裏會校驗映射和表結構)。
在這裏插入圖片描述
映射文件的引入:通過mapping標籤來引入,
在這裏插入圖片描述
3.Hibernate中的核心API:session、Transaction
1.Configuration類:用於創建Hibernate的配置對象
作用
加載核心配置文件:
  對於屬性文件的方式,hibernate.properties

Configuration cfg = new Configuration();

對於XML文件的方式,hibernate.cfg.xml

Configuration cfg = new Configuration().configure();

加載映射配置文件:

// 手動加載映射
configuration.addResource("包名/Customer.hbm.xml");

2.SessionFactory類:
概述:是Session工廠,SessionFactory內部維護了Hibernate的連接池和Hibernate的二級緩存。是線程安全的對象,一個項目創建一個對象即可。
3.Session類:
session:是Hibernate與數據庫連接的對象,該對象不是線程安全的(即不能定義爲全局的),session是與數據庫交互的橋樑。
session API:D:\hibernate-release-5.0.7.Final\documentation\javadocs\index.html,該文件打開後可以找到session的 API
保存操作:
session API中的方法:Serializable save(Object object)
在這裏插入圖片描述
示例:

    	//5.編寫代碼
    	Customer customer = new Customer();
    	customer.setCust_name("張三");
    	Serializable id = session.save(customer);
    	System.out.print(id);

查詢操作:
兩種查詢的方法:

T get(Class<T> c,Serializable id)
T load(Class<T> c,Serializable id)

在這裏插入圖片描述
在這裏插入圖片描述
查詢結果:
在這裏插入圖片描述
get方法與load方法的區別:
get方法
1.採用的是立即加載,執行到這行代碼的時候,就會馬上發送SQL語句去查詢;
2.查詢後返回的是真實的對象本身;
3.查詢一個找不到的對象的時候,返回null;
load方法
1.採用的是延遲加載(lazy懶加載),執行到這行代碼的時候,不會發生SQL語句,當使用這個對象(customer)的時候,纔會發送SQL語句;
2.查詢後,返回的是代理對象(即javassist-3.18.1-GA.jar包中利用javassist技術產生的代理);
3.查詢到一個找不到的對象的時候,返回ObjectNotFoundException;

修改操作:
兩種修改方式
  創建對象,進行修改
  先查詢,在查詢到的基礎上進行修改(推薦的方式
注:由於測試函數的前後代碼與前面一致,這裏只包含核心代碼(即5.編寫代碼部分)

    	//創建對象,進行修改
    	Customer customer = new Customer();
    	customer.setCust_id(1l);
    	customer.setCust_name("張三丰");
    	session.update(customer);
    	
    	//先查詢,在修改
    	Customer customer = session.get(Customer.class, 2l);
    	customer.setCust_name("張無忌");
    	session.update(customer);

刪除操作:
兩種刪除方式
  創建對象,進行刪除
  先查詢,在查詢到的基礎上進行刪除(推薦的方式

    	//創建對象,進行刪除
    	Customer customer = new Customer();
    	customer.setCust_id(4l);
    	session.delete(customer);
    	
    	//先查詢,再刪除
        Customer customer = session.get(Customer.class, 2l);
    	session.delete(customer);

其他操作:
保存或更新
當沒有setCust_id()函數時,執行保存的功能;當有setCust_id時,執行更新功能。

    	//保存
     	Customer customer = new Customer();
    	customer.setCust_name("張翠山");
    	session.saveOrUpdate(customer); 
    	//更新
    	Customer customer = new Customer();
    	customer.setCust_id(5l);
    	customer.setCust_name("趙敏");
    	session.saveOrUpdate(customer);

查詢所有
兩種方式:
  接收HQL方式
  接收SQL方式

    	//接收HQL:Hibernate Query Language 面向對象的查詢語言
    	Query query = session.createQuery("from Customer");
    	List<Customer> list = query.list();
    	for(Customer customer:list) {
    		System.out.println(customer);
    	}

    	//接收SQL
    	SQLQuery query = session.createSQLQuery("select *from cst_customer");
    	List<Object[]> list = query.list();
    	for(Object[] objects:list) {
    		System.out.println(Arrays.toString(objects));
    	}

測試結果:
HQL方式測試結果,
在這裏插入圖片描述
SQL方式測試結果,
在這裏插入圖片描述
4.Transaction對象:
Transaction:Hibernate中管理事務的對象;
主要方法
commit() :提交;
rollback() :回滾;

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