Quick Start Introduction to Hibernate framework of the first lecture --Hibernate

Overview Hibernate Framework

What is the framework?

Framework refers to the semi-finished software, it has completed some of the features.

JavaEE development of three-tier architecture

After understanding the basic concepts of the framework, Hibernate framework we take a look at what position JavaEE development of the classic three-tier architecture.

Tips: Although the Servlet + JSP + JavaBean + JDBC developers can use this architecture for all applications available in the market (have it, you will be able to conquer the world), but in the enterprise does not use (too bottom), it remains a Cock with ah! Enterprise development in general use SSH (Struts2 + Spring + Hibernate) and SSM (SpringMVC + Spring + MyBatis) .

Hibernate Overview

What is Hibernate?

We can see this from the degree of your mother's introduction to Hibernate:

From this, we can conclude that: Hibernate is a lightweight JDBC package, that is, we can use Hibernate to accomplish that we were done using JDBC operation, that is with the database interaction. It is used to Dao layer. All in all, Hibernate ORM framework is a persistence layer .

What is ORM?

When using traditional JDBC application development system, if it is a small application system, I do not think there is any trouble, but for the development of large-scale applications using JDBC will appeared to be inadequate. For example dozens, hundreds of table contains dozens of insertion, fields, SQL statements written not only long and tedious, error-prone; when data is read, it is necessary to write a plurality of concentrate was removed from the statement results getXxx information on the various fields, not only boring repetition, and the workload is very large. In order to improve the efficiency of programming data access layer, Gavin King has developed one of the most popular ORM framework, it is the Hibernate framework.
ORM is the use of so-called metadata mapping between database tables described objects and, automatically Java application object persisted to a relational database table. By operating Java object, you can perform operations on database tables. ORM can be understood as a link relational data and object, developers only need to focus on an object to link one end of the map. ORM principle as shown in FIG.

Said so much, nothing more than want to say that ORM is something, object-relational mapping (English: Object Relation Mapping, referred to as the ORM, or O / RM, or O / R mapping), refers to the object and relational one in Java database tables to establish a mapping relationship so that the operator can operate the object table in a database . It's that simple, why say so much!

Why learn Hibernate framework?

Compared with other technical operation of the database, Hibernate has the following advantages:

  • Hibernate JDBC access code to make a lightweight package database greatly simplifies the data access layer tedious repetitive coding, and reduces memory consumption, speed up the operation efficiency;
  • Hibernate is a JDBC-based persistence framework mainstream, is an excellent ORM implementation, simplifying the DAO (Data Access Object, Data Access Objects) layer coding its large degree;
  • Hibernate performance is very good, very good map of flexibility. It supports many relational databases, complex relationships from one-to-many;
  • 可扩展性强,由于源代码的开源以及API的开放,当本身功能不够用时,可以自行编码进行扩展。

总结:Hibernate是企业级开发中的主流框架,映射的灵活性很出色,并且它支持很多关系型数据库。

Hiberate框架学习目标

由于之前学过Hiberate框架,所以这就等于是在复习了。对于Hiberate框架的学习重点,可以总结为:

  1. 掌握Hiberate的基本配置——即搭建Hiberate开发环境;
  2. 掌握Hiberate常用API——即如何使用Hiberate框架进行开发;
  3. 掌握Hiberate的关联映射——解决表与表之间存在的关系问题,有1:n(一对多)、 1:1(一对一)、m:n(多对多)关系;
  4. 掌握Hiberate的检索方式——即掌握Hiberate的查询;
  5. 掌握Hiberate的优化方式——即提高Hiberate的效率。

Hibernate快速入门

介绍完Hibernate框架之后,我们来快速入门Hibernate,对其有一个直观的了解。

下载Hibernate5

大家可去官网下载Hibernate,我下载的是
这里写图片描述
所以,之后有关Hibernate的系列文章都是以这个版本为蓝图展开的。下载解压缩之后,可以看到如下目录结构:
这里写图片描述

其中,在lib/required目录下,包含运行Hibernate项目所必须的jar包:
这里写图片描述

创建一个普通的Java项目,导入Hibernate框架相关依赖jar包

创建一个普通的Java项目,例如hibernate_demo01,然后导入Hibernate框架相关依赖jar包。

  • 首先导入Hibernate开发必须的jar包,即lib/required目录下所有的jar包:
    这里写图片描述
  • 再导入MySQL数据库的驱动jar包:
    这里写图片描述
  • 最后导入日志记录相关的jar包:
    这里写图片描述
    导入完日志相关的jar包之后,我们还要导入日志记录文件,日志记录文件咋也是第一次接触,不知道咋写啊?没关系,找到project/etc/log4j.properties文件,很明显,它就是日志记录文件,将它拷贝复制到我们项目的src目录下,打开它,这里面的内容有点多啊!而且我们现在也不知道是什么意思,咋办?先跟着我将其内容精简为,后面我再来为大家做一点解释。

    ### direct log messages to stdout ###
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.err
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### direct messages to file mylog.log ###
    log4j.appender.file=org.apache.log4j.FileAppender
    log4j.appender.file.File=c\:mylog.log
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### set log levels - for more verbose logging change 'info' to 'debug' ###
    # error warn info debug trace
    log4j.rootLogger= info, stdout

这样工程的整个结构就变成:

创建数据库与表

正如前面所说,Hibernate是一个轻量级的JDBC封装,也就是说,我们可以使用Hibernate来完成原来我们使用JDBC完成的操作,也就是与数据库的交互操作。所以我们首先要创建数据库与表,这里我使用的数据库是MySQL。

create database hibernate_demo01;
use hibernate_demo01;
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;

创建实体类

我们在com.meimeixia.hibernate.demo01包中创建一个实体类——Customer.java,如下:

package com.meimeixia.hibernate.demo01;

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;
    
    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_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 + ", cust_source=" + cust_source
                + ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_phone=" + cust_phone
                + ", cust_mobile=" + cust_mobile + "]";
    }
    
}

创建Hibernate的相关配置文件

准备好以上工作之后,我们终于要踏入Hibernate的学习中了。首先我们要编写Hibernate的相关配置文件,Hibernate的相关配置文件分为两种:

  1. Xxx.hbm.xml:它主要是用于描述类与数据库中的表的映射关系;
  2. hibernate.cfg.xml:它是Hibernate框架的核心配置文件。

有关这两个配置文件的详细介绍,我后面会给大家讲解,如果就在这里弄的话,违背了我的初衷了,本文只是在教初学者怎样快速入门Hibernate。

创建映射配置文件

首先我们要学会如何编写映射配置文件,大家要知道编写完的映射配置文件应与实体类在同一个包下,并且名称应是类名.hbm.xml,所以我们要在com.meimeixia.hibernate.demo01包下创建一个Customer.hbm.xml文件,但是它的约束应该怎么写呢?可以在Hibernate的核心jar包——hibernate-core-5.0.7.Final.jar的org.hibernate包下查找到hibernate-mapping-3.0.dtd文件,打开该文件,找到如下内容:

然后复制黏贴到Customer.hbm.xml文件中即可。这里我先给出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">
    
<hibernate-mapping>
    <!-- 建立类与表的映射 -->
    <class name="com.meimeixia.hibernate.demo01.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框架所使用的,它主要包含了连接数据库的相关信息和Hibernate的相关配置等。现在我们要学会如何编写Hibernate的核心配置文件,大家也要知道编写完的核心配置文件应在src目录下,并且名称应是hibernate.cfg.xml,所以我们要在src目录下创建一个hibernate.cfg.xml文件,但是它的约束又应该怎么写呢?同样可以在Hibernate的核心jar包——hibernate-core-5.0.7.Final.jar的org.hibernate包下查找到hibernate-configuration-3.0.dtd文件,打开该文件,找到如下内容:

然后复制黏贴到hibernate.cfg.xml文件中即可。在这个文件中到底该如何配置呢?我们可以参考hibernate-release-5.0.7.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>
        <!-- 下面是三个必须要有的配置 -->
        <!-- 配置连接MySQL数据库的基本参数 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate_demo01</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">liayun</property>
        
        <!-- 配置Hibernate的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 下面两个是可选的配置哟! -->
        <!-- 打印sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化sql语句 -->
        <property name="hibernate.format_sql">true</property>
        
        <!-- 告诉Hibernate的核心配置文件加载哪个映射文件 -->
        <mapping resource="com/meimeixia/hibernate/demo01/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Hibernate快速入门开发测试

在com.meimeixia.hibernate.demo01包下创建一个单元测试类——HibernateDemo1.java。

package com.meimeixia.hibernate.demo01;

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

/**
 * Hibernate的入门案例
 * @author liayun
 *
 */
public class HibernateDemo1 {
    
    //保存用户的案例
    @Test
    public void demo1() {
        //1. 加载Hibernate的核心配置文件
        Configuration configuration = new Configuration().configure();
        //如果在Hibernate的核心配置文件没有设置加载哪个映射文件,则可手动加载映射文件
        //configuration.addResource("com/meimeixia/hibernate/demo01/Customer.hbm.xml");
        
        //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("张小敬aaa");
        
        session.save(customer);//保存一个用户
        
        //6. 事务提交
        transaction.commit();
        
        //7. 释放资源
        session.close();
        sessionFactory.close();
    }
    
}

测试如若都无任何问题,则我们就算入门Hibernate了。

Hibernate执行原理总结

可从度娘上看到如下文字:

码字不易,希望大家能够喜欢!

Guess you like

Origin www.cnblogs.com/yerenyuan/p/11298314.html