hibernate学习笔记(一)初识Hibernate

作者:叁念
本hibernate学习笔记教程所有资源百度云下载:链接:https://pan.baidu.com/s/1emXOxGbEzusjzPqJjLjMSg 密码:ulk1


一、初识Hibernate

1. 框架是什么?
  • 框架是用来提高开发效率的
  • 封装了好了一些功能.我们需要使用这些功能时,调用即可.不需要再手动实现.
  • 所以框架可以理解成是一个半成品的项目.只要懂得如何驾驭这些功能即可.
2.Hibernate 框架简介
  • Hibernate官方网站(下载地址):http://hibernate.org/
  • Hibernate 框架它简化了应用程序与数据库交互的过程,帮助我们完成数据库操作的过程。
  • hibernate是一款orm框架(object relationg mapping. 对象关系映射)即使用配置或者其他一些手段,将对象的信息和数据库中的表进行对应,完全面向对象操作数据库。
  • 另外Hibernate它是一个轻量级的jdbc封装,也就是说,我们可以使用hibernate来完成原来我们使用jdbc完成操作,就是与数据库的交互操作。
3.Hibernate 有何优势?
  • 操作数据库的时候,可以以面向对象的方式来完成.不需要书写SQL语句。
  • 即Hibernate 使用 XML 文件来处理映射 Java 类别到数据库表格中,并且不用编写任何代码。
  • 如果在数据库中或任何其它表格中出现结构变化,那么仅需要改变 XML 文件属性即可。
  • 抽象不熟悉的 SQL 类型,并为我们提供工作中所熟悉的 Java 对象。
4.Hibernate 的组成
  • 持久化类
  • 映射文件:用来描述类与表之间的关系,数据库有多少张表,至少应该有多少个映射文件 xxx.hbm.xml
  • 配置文件:完成数据库连接信息的填写,一般只有一个 hibernate.cfg.xml
5.认识Hibernate 中的一些对象?(了解)
  • Configuration:利用该类加载hibernate的配置文件,被用于创造一个 SessionFactory 对象
  • SessionFactory :是一个重量级对象,通常它都是在应用程序启动时创造然后留存以后使用,因此一般只有一个。
  • Session:被用于与数据库的物理连接。Session 对象是轻量级的,通常每次实例化都需要与数据库的交互。持久对象通过 Session 对象保存和检索。
  • Transaction:事务管理器
  • Query:Query 对象使用 SQL 或者 Hibernate 查询语言(HQL)字符串在数据库中来检索数据并创造对象。
  • Criteria :面向规则查询的检索对象

二、Hibernate 环境搭建

1.Hibernate 下载
  • 目录相关说明:
    documentation —— 存放hibernate的相关文件与API
    lib —— 存放hibernate编译和运行所依赖的jar包,其中required子目录下包含了运行hibernate项目必须的jar包
    project —— 存放hibernate各种相关的源代码与资源.
2.hibernate框架的搭建
2.1首先创建一个数据库名为hibernate,使用以下脚本创建对应的表

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;

2.2 创建项目并导入相关jar包
  • 创建一个java项目:File - New - Java Project - 填入项目名称:Hibernate01 - Finish
  • 项目右键 -New - Folder - 填入文件夹名libs - Finish
  • 打开之前下载的hibernate-release-5.3.1.Final找到以下目录hibernate-release-5.3.1.Final\lib\required,将里面的所有jar包(我这里有11个)拷入到libs文件夹下
  • 选择所有jar包右键 - Bulid Path - Add to Bulid Path ,完成后如图所示:
2.3 准备表持久化(实体)类

注意:持久化(实体)类中必须有一个默认的构造器,即空构造器

package com.sannian.bean;

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 Customer() {
        super();
    }

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

}
2.4 书写orm元数据(对象与表的映射配置文件 - XML格式),即xxx.hbm.xml

它主要是用于描述类与数据库中的表的映射关系.[映射配置文件]

  • 位置:它要与实体类在同一个包下.
  • 名称:类名.hbm.xml
  • 约束(声明):hibernate-mapping-3.0.dtd文件中可以找到,如图

Customer.hbm.xml内容如下【编写过程中如果出现不能自动提示的情况(即alt +/不能提示),请按照这篇文章进行操作:关于hibernate书写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="">
    <class name="com.sannian.bean.Customer" table="cst_customer">
        <id name="cust_id">
            <generator class="native"></generator>
        </id>
        <property name="cust_name"></property>
        <property name="cust_source"></property>
        <property name="cust_industry"></property>
        <property name="cust_level"></property>
        <property name="cust_linkman"></property>
        <property name="cust_phone"></property>
        <property name="cust_mobile"></property>
    </class>
</hibernate-mapping>

Customer.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">
<!-- 配置表与实体的关系 -->
<!-- package属性:填写一个包名,在元素内部凡是需要书写完整类名的属性,就可以直接写简单类名 -->
<hibernate-mapping package="">
    <!-- 
        class元素:配置实体与表的关系
            name:完整类名
            table:数据库表名
     -->
    <class name="" table="">
        <!-- 
            id元素:配置主键映射的属性
                name:填写主键对应的属性名
                column(可选):填写表中的主键列名,默认值:属性名
                type(可选):填写列(属性)的类型,hibernate会自动检测属性类型
                    每个属性类型有三种写法:java|hibernate|sql|
                not-null(可选):配置该属性是否不能为空,默认值:fasle
                length(可选):配置数据库中列的长度,默认值使用的数据类型的最大长度
         -->
        <id name="" column="">
            <!-- generator:主键生成策略 -->
            <generator class="native"></generator>
        </id>
        <!-- 
            property:除了id之外的普通属性映射
         -->
        <property name="cust_name"></property>

    </class>

</hibernate-mapping>
2.5 书写主配置文件,即hibernate.cfg.xml
  • 它是hibernate框架的核心配置文件。[核心配置文件]
  • 位置:在src下创建一个hibernate.cfg.xml
  • 约束:hibernate-configuration-3.0.dtd文件中可以找到
  • 书写内容:参考hibernate-release-5.3.1.Final\project\etc\hibernate.properties文件(了解):

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</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">6666</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="com/sannian/bean/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

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>
    <!-- 书写方式可以参照:hibernate-release-5.0.7.Final\project\etc\hibernate.properties -->
    <session-factory>
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///Hibernate</property>
        <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">183686</property>
        <!-- 数据库方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 把hibernate执行sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 把生成的sql格式化一下,方便阅读  -->
        <property name="hibernate.format_sql">true</property>
        <!--    自动建表
                #hibernate.hbm2ddl.auto create-drop     自动建表,每次框架运行会先删除之前的表,再建表,。最后会把表也删除
                #hibernate.hbm2ddl.auto create          自动建表,每次框架运行会先删除之前的表。最后数据会保留
                #hibernate.hbm2ddl.auto update          (推荐使用)不会建表,如果已存在才会进行操作,不存在也不会报错
                #hibernate.hbm2ddl.auto validate        验证,如果语法输入错误会报错!
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 
            引入ORM元数据配置,即加载映射文件
            路径填写:src目录下路径
         -->
        <mapping resource="com/sannian/bean/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
2.6 书写测试类

Hibernate的执行流程,代码如下( 注意:在hibernate中事务不是自动提交的):

  • 创建配置对象
  • 加载配置文件
  • 产生sessionFactory
  • 产生session
  • 开启事务
  • 完成操作
  • 事务提交

Test 内容如下:

package com.sannian.test;

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

import com.sannian.bean.Customer;

public class Test {
    public static void main(String[] args) {
        // 保存一个数据到数据库
        Configuration conf = new Configuration().configure();
        SessionFactory sessionFactory = conf.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        // -------------------------------------------
        Customer customer = new Customer();
        customer.setCust_name("sannian");
        session.save(customer);
        // -------------------------------------------
        transaction.commit();
        session.close();
        sessionFactory.close();
    }
}
2.7 运行查看数据库

控制台信息如下:

数据库信息如下:

至此,你已经学会了如何初步使用hibernate

三、hibernateAPI详解

3.1 Configuration
  • 作用:利用该类加载了hibernate的配置文件,创建SessionFactory
  • 执行流程:创建——加载主配置—— 加载orm元数据(扩展|了解)—— 创建sessionFactory
  • 演示代码:
        Configuration conf = new Configuration().configure();
        SessionFactory sessionFactory = conf.buildSessionFactory();
3.2 SessionFactory
  • 作用:打开一个新的session对象(数据库核心对象),获得一个与线程绑定的session对象
  • 详解:
    1. hibernate配置文件的信息、持久化类的信息、映射文件的信息全部在该类中
    2. sessionFactory对象有且只有一个(原因:负责保存和使用所有配置信息,消耗内存资源非常大)
    3. 生命周期是整个hibernate实例
    4. sessionFactory本身就是线程安全的
    5. 二级缓存在sessionFactory中存放
    6. sessionFactory和数据库的链接没有直接的关系
  • 演示代码:
        Configuration conf = new Configuration().configure();
        //根据文件hibernate.cfg.xml生成sessionFactory对象
        SessionFactory sessionFactory = conf.buildSessionFactory();
        //打开一个新的session
        Session openSession = sessionFactory.openSession();
        //获得一个与线程绑定的session[了解]
        Session currentSession = sessionFactory.getCurrentSession();
3.3 Session
  • 作用:一个session对象代表数据库的一个链接
  • 操作过程:
    1.session.save(xxx)
    2.去sessionFacyory中查询xxx.hbm.xml
    3.查找xxx.hbm.xml文件中的class元素的name属性值:该属性为持久化类的全名
    4.拼接insert into (来自于映射文件中的table属性)(字段名称…)(来自于映射文件中的prototype元素中的column属性的值拼接出来的getter方法),把方法拼接出来之后,就可以利用java的反射机制调用xxx对象的get方法
    5.利用jdbc技术执行该sql语句的过程
  • 演示代码:
public class SessionTransactionDemo {
    /**
     * session对象 功能: 表达hibernate与数据库之间的一次会话 类似于JDBC中的Connection
     * session是hibernate中的核心对象
     */
    public static void main(String[] args) {
        // 1.创建配置对象
        Configuration conf = new Configuration().configure();
        // 2.session工厂
        SessionFactory sessionFactory = conf.buildSessionFactory();
        // 3.获得session
        Session session = sessionFactory.openSession();

        // 4.获得事务
        // session.getTransaction();//获得一个事务对象
        Transaction transaction = session.beginTransaction();// 获得并启动一个事务(推荐)

        // --------------------------
        //1.增
        Customer customer = new Customer();
        customer.setCust_name("yujie");
        session.save(customer);

        //2.查
        Customer customer1 = session.load(Customer.class, 2l);
        System.out.println(customer1.getCust_name());
        //3.改
        Customer customer2 = session.load(Customer.class, 2l);
        customer2.setCust_name("temp");
        session.update(customer2);
        //4.删
        Customer customer3 = session.load(Customer.class, 2l);
        session.delete(customer3);

        transaction.commit(); // 事务提交
//      transaction.rollback(); // 事务回滚
        session.close();
        sessionFactory.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36868342/article/details/80604925
今日推荐