Hibernate快速入门详细讲解

Hibernate框架介绍

什么是Hibernate

Hibernate是一种ORM框架,全称为 Object_Relative DateBase-Mapping,在Java对象与关系数据库之间建立某种映射,以实现直接存取Java对象

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用。

从中,我们可以得出这样的结论:Hibernate是一个轻量级的JDBC封装,也就是说,我们可以使用Hibernate来完成原来我们使用JDBC完成的操作,也就是与数据库的交互操作。它是在dao层去使用的。

 

为什么要使用Hibernate?

原因如下:

Hibernate对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码。
Hibernate是一个基于JDBC的主流持久化框架,是一个优秀的ORM实现,它很大程度的简化了dao层编码工作。
总结:Hibernate是企业级开发中的主流框架,映射的灵活性很出色。它支持很多关系型数据库。

 

什么是ORM?

在介绍Hibernate的时候,说了Hibernate是一种ORM的框架。那什么是ORM呢?ORM是一种思想

  • O代表的是Objcet
  • R代表的是Relative
  • M代表的是Mapping

ORM->对象关系映射....ORM关注是对象与数据库中的列的关系

 

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,对其有一个直观的了解。

学习一个框架无非就是三个步骤:

  • 引入jar开发包
  • 配置相关的XML文件
  • 熟悉API

hibernate的基本代码可以通过idea或者eclipse生成,我有一篇通过idea生成hibernate的笔记,有兴趣的同学可以看一下

https://blog.csdn.net/Yang_Hui_Liang/article/details/88662090

项目的目录结构

 

1、如果是maven项目就配置hibernate的pom文件以及mysql的pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.et</groupId>
  <artifactId>hibernate-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <!--hibernate 的配置文件-->
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.0.0.Final</version>
    </dependency>

    <!-- mysql数据库的驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>

  </dependencies>

  <!--插件 maven编译的时候不会编译java目录下的xml文件 所以需要配置这个查询 不然会找不到文件的路径-->
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

2.创建一个实体对象

package cn.et.dao;

public class StudentEntity{
    private String sid;
    private String sname;
    private String gid;
    private String sage;
    private String ssex;

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getGid() {
        return gid;
    }

    public void setGid(String gid) {
        this.gid = gid;
    }

    public String getSage() {
        return sage;
    }

    public void setSage(String sage) {
        this.sage = sage;
    }

    public String getSsex() {
        return ssex;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex;
    }
}


 

3.配置配置文件

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

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

 

配置 StudentEntity.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>
    <!--
        name:即实体类的全名
        table:映射到数据库里面的那个表的名称
        catalog:数据库的名称
    -->
    <class name="cn.et.dao.StudentEntity" table="student" schema="test">
        <!-- class下必须要有一个id的子元素 -->
        <!-- id是用于描述主键的 必须要指定 不然会报错的-->
        <id name="sid" column="sid"></id>
        <!-- 使用property来描述属性与字段的对应关系如果length忽略不写,且你的表是自动创建这种方案,那么length的默认长度是255-->
        <property name="sname" column="sname"/>
        <property name="gid" column="gid"/>
        <property name="sage" column="sage"/>
        <property name="ssex" column="ssex"/>
    </class>
</hibernate-mapping>

配置 hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
      <!-- 配置关于数据库连接的四个项:driverClass  url username password -->
      <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.username">root</property>
      <property name="connection.password">123456</property>

      <!-- 可以将向数据库发送的SQL语句显示出来 -->
      <property name="hibernate.show_sql">true</property>

      <!-- 格式化SQL语句 -->
      <!--<property name="hibernate.format_sql">true</property>-->

      <!-- 数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql-->
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

      <!-- 配置hibernate的映射文件所在的位置 -->
      <!--<mapping resource="cn/et/dao/StudentEntity.hbm.xml"/>-->
  </session-factory>
</hibernate-configuration>

 

4.写一个测试类

package cn.et.controller;

import cn.et.dao.StudentEntity;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import java.util.List;

public class HibernateTest {
    //获取加载配置管理类 不给参数就默认加载hibernate.cfg.xml文件,
    private static final Configuration config = new Configuration().configure().addClass(StudentEntity.class);
    //创建Session工厂对象
    private static final SessionFactory sessionFactory = config.buildSessionFactory();
    //得到Session对象
    private static final Session session = sessionFactory.openSession();

    public static void main(String[] args) {
//        getQBCStudent();     //查询
//        insertStudent();  //添加
//        deleteStudent();  //删除
//        updateStudent();  //修改
        getHQLStudent();

    }

    /**
     * 添加
     */
    public static void insertStudent(){
        //使用Hibernate操作数据库,都要开启事务,得到事务对象
        session.beginTransaction();

        StudentEntity studentEntity =new StudentEntity();
        studentEntity.setSid("aa");
        studentEntity.setGid("bb");
        studentEntity.setSage("30");
        studentEntity.setSname("kkk");
        studentEntity.setSsex("女");

        //调用添加的方法
        session.save(studentEntity);

        // 事务提交
        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }

    /**
     * 删除
     */
    public static void deleteStudent(){
        // 开启事务
        session.beginTransaction();
        StudentEntity studentEntity =new StudentEntity();
        studentEntity.setSid("aa");

        //调用删除的方法
        session.delete(studentEntity);

        // 事务提交
        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }

    /**
     * 修改
     */
    public static void updateStudent(){
        // 开启事务
        session.beginTransaction();

        StudentEntity studentEntity =new StudentEntity();
        studentEntity.setSid("2");
        studentEntity.setSage("200");

        //调用修改的方法
        session.update(studentEntity);

        // 事务提交
        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }

    /**
     * QBC查询
     */
    public static void getQBCStudent(){
        //创建关于StudentEntity对象的criteria对象
        Criteria criteria = session.createCriteria(StudentEntity.class);

        //添加条件
        criteria.add(Restrictions.eq("ssex", "男"));
        criteria.add(Restrictions.like("sname","%小%"));

        //查询全部数据
        List<StudentEntity> list = criteria.list();

        for (StudentEntity student : list){
            System.out.println(student.getSid()+"=="+student.getSname()+"=="+student.getGid()+"=="+student.getSage()+"=="+student.getSsex());
        }
    }

    /**
     * HQL查询
     */
    public static void getHQLStudent(){
        Query query =session.createQuery("from StudentEntity where sname=?");
        query.setParameter(0,"张三");
        List<StudentEntity> list = query.list();
        for (StudentEntity student : list){
            System.out.println(student.getSid()+"=="+student.getSname()+"=="+student.getGid()+"=="+student.getSage()+"=="+student.getSsex());
        }
    }
}

 

下面来讲解一下配置

Configuration

配置管理类:主要管理配置文件的一个类

拥有一个子类AnnotationConfiguration,也就是说:我们可以使用注解来代替XML配置文件来配置相对应的信息

 

configure方法

configure()方法用于加载配置文件

  • 加载主配置文件的方法
    • 如果指定参数,那么加载参数的路径配置文件
    • 如果不指定参数,默认加载src/目录下的hibernate.cfg.xml

 

buildSessionFactory方法

buildSessionFactory()用于创建Session工厂

 

SessionFactory

SessionFactory-->Session的工厂,也可以说代表了hibernate.cfg.xml这个文件...hibernate.cfg.xml的就有<session-factory>这么一个节点

 

openSession方法

创建一个Session对象

 

getCurrentSession方法

创建Session对象或取出Session对象

 

Session

Session是Hibernate最重要的对象,Session维护了一个连接(Connection),只要使用Hibernate操作数据库,都需要用到Session对象

 

beginTransaction方法

开启事务,返回的是一个事务对象....Hibernate规定所有的数据库操作都必须在事务环境下进行,否则报错!

 

Hibernate执行流程图

 

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

要是看完这个还有疑惑的同学可以看下这位兄台的博客写的比较详细 点我

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值