1. 程式人生 > >Hibernate學習(1)- 初識

Hibernate學習(1)- 初識

his HA logs ply func 對數 事務管理 arch 優化

一、概念引入

1、持久化:

  狹義概念:數據存儲在物理介質不會丟失。

  廣義概念:對數據的CRUD操作都叫做持久化。

2、加載: hibernate裏,數據從數據庫中加載到session。

3、ORM -- Object Relation Mapping

技術分享圖片

好處:

  解決阻抗不匹配:對象與關系數據庫不匹配。

  沒有侵入性:在代碼中不用去繼承或者實現hibernate類或實現hibernate提供的接口。

  hibernate:一個ORM的輕量級框架,解決持久化問題,是程序員可以從編寫復雜的JDBC工作中解放,專註於業務,提高程序員的開發效率。

二、第一個Hibernate程序

1、資源包介紹

技術分享圖片

  •  documentation :相關文檔
  •  lib :相關的jar包
  •  project :相關資源文件、模板文件、源碼等

2、搭建hibernate環境
a)相關jar包 (required下的jar)

技術分享圖片 技術分享圖片

補充一點:hibernate所處的位置關系:

hibernate.cfg.xml 主要是配置信息
*.hbm.xml 實體與表的映射關系

技術分享圖片 技術分享圖片

b)添加配置文件(hibernate.cfg.xml)

<!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="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_test</property>
<property name="connection.username">json</property> <property name="connection.password">123456</property> <!-- 第二部分:其他相關配置 --> <!-- 數據庫方言 - 配置hibernate方言,可針對特定的數據庫優化。 --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 是否在運行時候sql語句輸出到控制臺,編碼階段便於測試的。(默認設置為true)--> <property name="show_sql">true</property> <!-- 輸出在控制臺sql語句是否進行格式化,便於閱讀。(默認設置為true) --> <property name="format_sql">true</property> <!-- 可幫助由java代碼生成數據庫腳本,進而生成具體表結構。如:create/update/create-drop/validate create: 每次都重新建表,原來的表刪除,同時數據全部清楚重新插入數據。(每次加載hibernate,重新創建數據庫表結構,這就是導致數據庫表數據丟失的原因。) create-drop: 每次在創建sessionFactory時執行創建表,當調用sessionFactory的close方法的時候,刪除表 (在實際項目中不用) update: 只是根據映射文件去和數據庫中的表對應起來,如果不一致,就更新表的結構 validate: 加載hibernate時,驗證創建數據庫表結構,如果是不同的話則不創建表。 PS: 1.請慎重使用 hbm2ddl.auto 此參數,沒必要就不要隨便用。 2.如果發現數據庫表丟失,請檢查hibernate.hbm2ddl.auto的配置 --> <property name="hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration>

c)創建數據庫

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `pwd` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

d)創建實體對象

package com.demo.pojo;

public class User {
    private Long id;
    private String name;
    private String pwd;
    
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", pwd=" + pwd;
    }
}

e)編輯*.hbm.xml文件

文件名一般為實體類User對應的名稱 User.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 package="org.hibernate.test.cache.infinispan.functional.entities">
    <class name="com.demo.pojo.User" table="user">
        <id name="id"  type="java.lang.Long">
            <!-- 主鍵生成策略 -->
            <generator class="identity"/> <!--  自增 -->
        </id>
        <!-- 實體類屬性 -->
        <property name="name" type="java.lang.String"/>
        <property name="pwd" type="java.lang.String"/>        
    </class>
</hibernate-mapping>

f)測試
前提:將*.hml.xml文件 加入到hibernate.cfg.xml中

<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_test</property>
        <property name="connection.username">json</property>
        <property name="connection.password">123456</property>
        
        
        <!-- 第二部分:其他相關配置 -->
        <!-- 數據庫方言  - 配置hibernate方言,可針對特定的數據庫優化。  -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 是否在運行時候sql語句輸出到控制臺,編碼階段便於測試的。(默認設置為true)-->
        <property name="show_sql">true</property>
        <!-- 輸出在控制臺sql語句是否進行格式化,便於閱讀。(默認設置為true) -->
        <property name="format_sql">true</property>
        <!-- 
            可幫助由java代碼生成數據庫腳本,進而生成具體表結構。如:create/update/create-drop/validate
                create: 每次都重新建表,原來的表刪除,同時數據全部清楚重新插入數據。(每次加載hibernate,重新創建數據庫表結構,這就是導致數據庫表數據丟失的原因。)  
                create-drop: 每次在創建sessionFactory時執行創建表,當調用sessionFactory的close方法的時候,刪除表       (在實際項目中不用)
                update: 只是根據映射文件去和數據庫中的表對應起來,如果不一致,就更新表的結構
                validate: 加載hibernate時,驗證創建數據庫表結構,如果是不同的話則不創建表。
                
            PS:
                1.請慎重使用 hbm2ddl.auto 此參數,沒必要就不要隨便用。  
                2.如果發現數據庫表丟失,請檢查hibernate.hbm2ddl.auto的配置  
        -->
        <property name="hbm2ddl.auto">update</property>
        
        
        <!-- 第三部分:加載所有的映射(*.hbm.xml) -->
        <mapping resource="com/demo/pojo/User.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

測試類:

package com.demo.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.jupiter.api.Test;

import com.demo.pojo.User;

public class QueryTest {

    @Test
    public void connectTest() {
        /*
        //1、新建Configuration對象 (Configuration管理加載配置文件)
        Configuration config = new Configuration().configure();
        //2、通過configuration得到SessionFactory對象
        //3、通過SessionFactory得到Session對象
        //hibernate3.x 中的寫法
        SessionFactory session = config.buildSessionFactory();
        
        //hibernate4.3之前 ~~ 4.0
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession();
    
        //hibernate4.3  其中的一種 獲取SessionFactory的方法
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
        SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession(); 
        */

        //Hibernate5.1 的獲取SessionFactory的方法
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        //4、通過Session得到Transaction對象 (兩種寫法)
        //Transaction transaction = session.getTransaction();
        //transaction.begin();
        Transaction transaction = session.beginTransaction();
        //5、保存數據
        User user = new User();
        user.setName("張三");
        user.setPwd("123456");
        session.save(user);
        //6、提交事務
        transaction.commit();
        //7、關閉Session
        session.close();
    }
    
    @Test
    public void queryTest() {
        //Hibernate5.1 的獲取SessionFactory的方法
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        //5、保存數據
        User user = session.get(User.class, 8L);
        System.out.println(user);
        //6、提交事務
        //7、關閉Session
        session.close();
    }
    
    @Test
    public void saveTest() {
        //Hibernate5.1 的獲取SessionFactory的方法
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        //4、通過Session得到Transaction對象
        Transaction transaction = session.beginTransaction();
        //5、保存數據
        User user = new User();
        user.setName("張三");
        user.setPwd("123456");
        session.save(user);
        //6、提交事務
        transaction.commit();
        //7、關閉Session
        session.close();
    }

} 

PS:

  1. SessionFactroy對象: 是一個session工廠,是一個重量級的對象,在一個應用中最好也是單例的,是一個線程安全的,屬於進程級的對象。
  2. Session對象:使用hibernate進行數據庫操作,主要使用session。session可以理解為對connction對象的一個包裝。session對象中提供了對數據庫的CRUD操作,Session是一個線程不安全的對象,生命周期很短暫,一般和事務一一對應。Session又稱為hibernate的一級緩存。Session又是Transaction對象的工廠。
  3. Transaction對象:事務管理對象,通過Session獲取該對象。
  4. Query 對象: 條件查詢

PS:源碼地址 https://github.com/JsonShare/hibernate-demo

PS:原文地址 http://www.cnblogs.com/JsonShare/p/8647269.html

Hibernate學習(1)- 初識