一、Hibernate-入门

1、概述

一、什么是Hibernate:

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了很是轻量级的对象封装,它将POJO与数据库表创建映射关系,是一个全自动的orm框架,hibernate能够自动生成SQL语句,自动执行,使得Java程序员能够为所欲为的使用对象编程思惟来操纵数据库。 Hibernate能够应用在任何使用JDBC的场合,既能够在Java的客户端程序使用,也能够在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate能够在应用EJB的JaveEE架构中取代CMP,完成数据持久化的重任。java

 

二、什么是ORM:

ORM:Object Relational Mapping(对象关系映射)。指的是将一个Java中的对象与关系型数据库中的表创建一种映射关系,从而操做对象就能够操做数据库中的表。mysql

 

三、Hibernate的做用:

一、对象化。程序员

hibernate可让开发人员以面相对象的思想来操做数据库。jdbc只能经过SQL语句将元数据传送给数据库,进行数据操做。而hibernate能够在底层对元数据和对象进行转化,使得开发者只用面向对象的方式来存取数据便可。sql

二、更好的移植性。数据库

hibernate使用xml或JPA的配置以及数据库方言等等的机制,使得hibernate具备更好的移植性,对于不一样的数据库,开发者只须要使用相同的数据操做便可,无需关心数据库之间的差别。而直接使用JDBC就不得不考虑数据库差别的问题。编程

三、开发效率高。缓存

hibernate提供了大量的封装(这也是它最大的缺点),不少数据操做以及关联关系等都被封装的很好,开发者不需写大量的sql语句,这就极大的提升了开发者的开发效率。安全

四、缓存机制的使用。session

hibernate提供了缓存机制(session缓存,二级缓存,查询缓存),对于那些改动不大且常用的数据,能够将它们放到缓存中,没必要在每次使用时都去查询数据库,缓存机制对提高性能大有裨益。架构

                                                                   

 

 

 

 2、建立项目

一、下载的hibernate目录:

                  

documentation           :Hibernate开发的文档

lib                               :Hibernate开发包

 required                    :Hibernate开发的必须的依赖包

 optional                    :Hibernate开发的可选的jar包

  project                     :Hibernate提供的项目

二、建立一个基础的Java项目,导入对应的Jar便可。

                    

 

 

 

三、建立表

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;

 

 

四、建立对应的实体类

package com.turtle.dao;

import java.io.Serializable;

public class Customer implements Serializable {

    // 客户编号(主键)
    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;
    }
}

 

 

五、建立映射

映射须要经过XML的配置文件来完成,这个配置文件能够任意命名。尽可能统一命名规范(类名.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.turtle.dao.Customer" table="cst_customer">
        <!-- 创建类中的属性与表中的主键对应 -->
        <id name="cust_id" column="cust_id" >
            <generator class="native"/>
        </id>

        <!-- 创建类中的普通的属性和表的字段的对应 -->
        <property name="cust_name" column="cust_name" length="32" />
        <property name="cust_source" column="cust_source" length="32"/>
        <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>

 

【class标签的配置】

  标签用来创建类与表的映射关系

  属性:

  name                :类的全路径

  table                 :表名(类名与表名一致,table能够省略)

  catalog             :数据库名

 

【id标签的配置】

  标签用来创建类中的属性与表中的主键的对应关系

  属性:

  name                :类中的属性名

  column             :表中的字段名(类中的属性名和表中的字段名若是一致,column能够省略)

  length               :长度

  type                   :类型

 

【property标签的配置】

  标签用来创建类中的普通属性与表的字段的对应关系

  属性:

  name                :类中的属性名

  column             :表中的字段名

  length               :长度

  type                   :类型

  not-null            :设置非空

  unique              :设置惟一

 

六、建立一个Hibernate的核心配置文件

Hibernate的核心配置文件的名称: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_demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</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>
        <!-- 自动建立表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 配置C3P0链接池 -->
        <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
        <!--在链接池中可用的数据库链接的最少数目 -->
        <property name="c3p0.min_size">5</property>
        <!--在链接池中全部数据库链接的最大数目  -->
        <property name="c3p0.max_size">20</property>
        <!--设定数据库链接的过时时间,以秒为单位,
        若是链接池中的某个数据库链接处于空闲状态的时间超过了timeout时间,就会从链接池中清除 -->
        <property name="c3p0.timeout">120</property>
        <!--每3000秒检查全部链接池中的空闲链接 以秒为单位-->
        <property name="c3p0.idle_test_period">3000</property>

        <mapping resource="com/turtle/dao/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 

  必须的配置

    链接数据库的基本的参数

    驱动类

    url路径

    用户名

    密码

    方言

 可选的配置

   显示SQL          :hibernate.show_sql

    格式化SQL     :hibernate.format_sql

    自动建表        :hibernate.hbm2ddl.auto

      none                 :不使用hibernate的自动建表

      create               :若是数据库中已经有表,删除原有表,从新建立,若是没有表,新建表。(测试)

      create-drop     :若是数据库中已经有表,删除原有表,执行操做,删除这个表。若是没有表,新建一个,使用完了删除该表。(测试)

      update             :若是数据库中有表,使用原有表,若是没有表,建立新表(更新表结构)

     validate            :若是没有表,不会建立表。只会使用数据库中原有的表。(校验映射和表结构)。

 映射文件的引入    

    引入映射文件的位置

  <mapping resource="com/turtle/dao/Customer.hbm.xml"/>

 

七、编写测试代码

package com.turtle.test;

import com.turtle.dao.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class TestCustomer {
    public static  void main(String [] args){
        // 一、加载配置文件
        Configuration configuration = new Configuration().configure();
        // 二、建立一个SessionFactory对象
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 三、建立Session对象
        Session session = sessionFactory.openSession();
        // 四、开启事务
        Transaction transaction = session.beginTransaction();
        try{
            Customer customer = new Customer();
            customer.setCust_name("测试用户1");
            // 调用Hibernate自带的API来进行保存操做
            session.save(customer);
            // 提交事务
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            // 回滚事务
            transaction.rollback();
        }finally {
            // 关闭链接
            session.close();
        }
    }
}

 

 八、控制台打印的SQL语句和数据的结果表数据

                                                                          

 

                                                                          

3、Hibernate的API

一、Configuration:Hibernate的配置对象

  做用:加载核心配置文件

 

hibernate.properties

Configuration cfg = new Configuration();

 

 hibernate.cfg.xml

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

  加载映射文件

 

// 手动加载映射

configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml");

 

二、 SessionFactory:Session工厂

SessionFactory内部维护了Hibernate的链接池和Hibernate的二级缓存(不讲)。是线程安全的对象。一个项目建立一个对象便可。

 

三、Session:相似Connection对象是链接对象

Session表明的是Hibernate与数据库的连接对象。不是线程安全的。与数据库交互桥梁。

  Session中的API

  保存方法:

    Serializable save(Object obj);

  查询方法:

    T get(Class c,Serializable id);

    T load(Class c,Serializable id);

  修改方法

   void update(Object obj);

  删除方法

    void delete(Object obj);s

  保存或更新

    void saveOrUpdate(Object obj)

 

四、  Transaction:事务对象

Hibernate中管理事务的对象。

    commit();

    rollback();

相关文章
相关标签/搜索