hibernate框架的学习--第一天

一.   hibernate是什么

 1.   框架是什么

      1).框架是用来提高开发效率的

      2).封装了好了一些功能.我们需要使用这些功能时,调用即可.不需要再手动实现.

      3).所以框架可以理解成是一个半成品的项目.只要懂得如何驾驭这些功能即可.

    2.  hibernate框架是什么

     

    3.   hibernate的好处

        1)   操作数据库的时候,可以以面向对象的方式来完成.不需要书写SQL语句

    4.  hibernate是一款orm框架

           orm:object relationg mapping. 对象关系映射

              

      1)   orm分4级

         hibernate属于4级:完全面向对象操作数据库

         mybatis属于2级

         dbutils属于1级

二.   hibernate框架的搭建

     1.导包

       1)Jar包

    

       2).   驱动包

     

      2. 创建数据库,准备表,实体 

      1)数据库表

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_user_id` bigint(32) DEFAULT NULL COMMENT '负责人id',
  `cust_create_id` bigint(32) DEFAULT NULL COMMENT '创建人id',
  `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`)
)

 2)实体

/**
 * 客户实体类
 * @author vanguard
 *
 */
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 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;
    }
    
    @Override
    public String toString() {
        return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name
                + "]";
    }
    
}

    3.  书写orm元数据(对象与表的映射配置文件)

  1)导入约束

       2)

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

       3)ORM元数据

      

    4   书写主配置文件

     

     

    

    5.书写代码测试

/**
 * hibernate快速入门
 * 使用hibernate操作客户表b
 * @author vanguard
 *
 */
public class Demo {
    @Test
    public void fun() {
        //1. 创建Configuration对象并加载主配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 根据配置文件,创建SessionFactory对象
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 获得session对象
        Session session = sf.openSession();
        
        //4. 开启事务
        Transaction tx = session.beginTransaction();
        /********************************/
        Customer c = new Customer();
        c.setCust_name("google");
        //执行保存
        session.save(c);
        
        /********************************/
        // 提交事务
        tx.commit();
        //释放资源
        session.close();
        sf.close();
    }
}    

三   配置文件详解

     1    orm元数据

       

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5     
 6 <!-- 配置表与实体对象的关系 -->
 7 <!-- package属性:填写一个包名,在元素内部凡是需要完整的类名的属性,直接写简化的类名 -->
 8 <hibernate-mapping package="com.java.domain">
 9 
10     <!-- 
11         class元素:配置实体与表的对应关系
12         name:完整类名
13         table:数据库表名
14      -->
15     <class name="Customer" table="cst_customer">
16     
17         <!-- 
18             id元素:配置主键映射的属性
19             name:填写主键对应的属性名
20             column(可选):填写表中的主键列名.默认值:主键会默认使用属性名
21             type(可选):填写列(属性)的类型。hibernate会自动检测实体的属性类型
22                         每个类型有三种填法:java类型|hibernate类型|数据库类型
23             not-null(可选):配置该属性(列)是否不能为空。默认值:false
24             length(可选):配置数据库中列的长度。默认值:使用数据库类型的最大长度
25          -->
26         <id name="cust_id" column="cust_id">
27             <!-- 主键生成策略(7个)
28                  identity:主键自增,有数据库维护主键值,录入时不需要指定主键
29                  sequence:Oracle中的主键生成策略,
30                  increment(了解):主键自增,由hibernate来维护,每次插入前会先查询表中id最大值,+1作为新主键
31                  hilo(了解):高低位算法,主键自增,由hibernate维护,开发时不使用
32                  native:hile+sequence+identity 自动三选一策略
33                  uuid:产生随机字符串作为主键,主键必须是string类型
34                  assigned:自然主键生成策略,hibernate不会管理主键值,由开发人员录入
35              -->
36             <generator class="native"></generator>
37         </id>
38         
39         <!-- 
40             property元素:除id之外的普通属性的映射
41             name:填写属性名
42             column(可选):填写列名 默认值:会默认使用属性名
43             type(可选):填写列(属性)的类型。hibernate会自动检测实体的属性类型
44                         每个类型有三种填法:java类型|hibernate类型|数据库类型
45             not-null(可选):配置该属性(列)是否不能为空。默认值:false
46             length(可选):配置数据库中列的长度。默认值:使用数据库类型的最大长度
47          -->
48         <property name="cust_name" column="cust_name">
49             <!-- <column name="cust_name" sql-type="varchar"></column> -->
50         </property>    
51         <property name="cust_source" column="cust_source"></property>
52         <property name="cust_industry" column="cust_industry"></property>
53         <property name="cust_level" column="cust_level"></property>
54         <property name="cust_linkman" column="cust_linkman"></property>
55         <property name="cust_phone" column="cust_phone"></property>
56         <property name="cust_mobile" column="cust_mobile"></property>
57     </class>
58 </hibernate-mapping>

  2  hibernate主配置 

          1)  必选属性配置(5个)

        

<!-- 必选属性配置(5个) -->
        
        <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///crm</property>
        <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">root</property>
        <!-- 
            数据库方言:
            不同数据库中,sql语法略有区别,指定方言可以让hibernate框架再生成sql语句时,针对数据库的方言生成
            sql99标准: DDL:数据定义语言 库表的增删改查
                       DCL:数据控制语言 事务 权限
                       DML:数据操纵语言 增删改查
            注意:mysql在选择方言时,选择最短的方言 org.hibernate.dialect.MySQLDialect              
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    

            

         2)    可选属性配置(3个)

       

<!-- 可选的配置(3个) -->
        <!-- 
        #hibernate.show_sql true
        #hibernate.format_sql true     
        -->
        <!-- 将hibernate生成的sql语句打印在控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成sql语句格式化(缩进) -->
        <property name="hibernate.format_sql">true</property>
        <!--     
        ## auto schema export 自动导出表结构  自动建表
        #hibernate.hbm2ddl.auto create 自动建表,每次运行框架都会创建新的表,以前的表会被覆盖,数据会丢失(开发环境测试使用)
        #hibernate.hbm2ddl.auto create-drop 自动建表,每次运行框架运行结束都会删除所用表(测试环境中使用)
        #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表,如果已经存在不会再生成,如果表有变动,自动更新表(不会删除任何数据)
        #hibernate.hbm2ddl.auto validate 校验:不自动建表,每次启动会校验数据库中的表是否正确,不正确则校验失败,抛出异常
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>

  3) 元数据引入配置

         

        <!-- 
            引入orm数据源
            路径填写:src下的路径
         --> 
        <mapping resource="com/java/domain/Customer_hbm.xml"/>

四、hibernateAPI详解

 1   Configuration

       

/**
     * Configuration
     */
    @Test
    public void fun1() {
        //1. 创建configuration对象,调用空参构造
        Configuration configure = new Configuration();
        
        //2. 读取配置文件
        Configuration conf = configure.configure();
        
        //3. 读取指定的orm元数据(扩展),如果主配置中已经引入映射配置文件不需要手动加载
//        conf.addResource(resourceName);
//        conf.addClass(persistentClass);
        
        //4. 根据配置文件,创建SessionFactory
        SessionFactory sessionFactory = conf.buildSessionFactory();
        
        sessionFactory.close();
    }   

    2    SessionFactory 

      SessionFactory对象
      功能:用于创建数据库核心对象session对象的工厂。简单说就是创建session对象。
      注意:1. sessionFactory用于保存和使用所有配置信息,消耗内存资源非常大
               2. sessionFactory属于线程安全的对象
     结论:保证WEB应项目中,只创建一个sessionFactory
/**
     * SessionFactory对象
     * 功能:用于创建数据库核心对象session对象的工厂。简单说就是创建session对象。
     * 注意:1. sessionFactory用于保存和使用所有配置信息,消耗内存资源非常大
     *          2. sessionFactory属于线程安全的对象
     * 结论:保证WEB应项目中,只创建一个sessionFactory
     * 
     */
    @Test
    public void fun2() {
        //1. 创建configuration对象,并读取配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 根据配置文件,创建SessionFactory
        SessionFactory sessionFactory = conf.buildSessionFactory();
        
        //3. 打开一个新的session对象
        Session session = sessionFactory.openSession();
        //获得与线程绑定的esssion对象
        Session session2 = sessionFactory.getCurrentSession();
        
        sessionFactory.close();
    }

      3    Session 

  Session对象
  功能:表示hibernate框架与数据库之前的连接(会话),sesssion类似于
  JDBC的connection对象,还可以完成对数据库的增删改查操作,
  session是hibernate操作数据库的核心对象

     

/**
     * Session对象
     * 功能:表示hibernate框架与数据库之前的连接(会话),sesssion类似于
     *          JDBC的connection对象,还可以完成对数据库的增删改查操作,
     *          session是hibernate操作数据库的核心对象
     */
    @Test
    public void fun3() {
        //1. 创建Configuration对象,并加载配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 建立sessionfactory工厂对象
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打开一个新的session对象
        Session session = sf.openSession();
        
        //4. 获得事务
        Transaction tx = session.getTransaction();
        
        //5. 开启事务
        tx.begin();
        
        
    }

         1) session对数据库进行增加操作 

   /**
     * session对数据库进行增加的操作
     */
    @Test
    public void fun1() {
        //1. 创建Configuration对象,并加载配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 建立sessionfactory工厂对象
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打开一个新的session对象
        Session session = sf.openSession();
        
        //4. 开启事务并获得操作事务的对象
        Transaction tx = session.beginTransaction();
        /*********操作数据库********************/
        
        Customer c = new Customer();
        c.setCust_name("百度");
        session.save(c);
        
        /**************************************/
        //提交事务
        tx.commit();
        //释放资源
        session.close();
        sf.close();
        
    }

         2)session对数据进行查询操作

          

/**
     * 对数据库进行查询操作
     */
    @Test
    public void fun2() {
        //1. 创建configuraion对象并加载配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 创建sessionfactory工厂
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打开一个新的session对象
        Session session = sf.openSession();
        
        //4. 开启事务并获得操作事务的对象
        Transaction tx = session.beginTransaction();
        
        //5. 对数据库进行删除操作
        //获得需要修改的对象
        Customer customer = session.get(Customer.class, 2l);
        System.out.println(customer);
        //6. 提交事务
        tx.commit();
        
        //7. 释放资源
        session.close();
        sf.close();
    }

        3)session对数据库进行删除操作

         

/**
     * session对数据库进行删除操作
     */
    @Test
    public void fun3() {
        //1. 创建configuraion对象并加载配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 创建sessionfactory工厂
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打开一个新的session对象
        Session session = sf.openSession();
        
        //4. 开启事务并获得操作事务的对象
        Transaction tx = session.beginTransaction();
        
        //5. 对数据库进行删除操作
        //获得需要删除的对象
        Customer customer = session.get(Customer.class, 1l);
        //执行删除操作
        session.delete(customer);
        
        //6. 提交事务
        tx.commit();
        
        //7. 释放资源
        session.close();
        sf.close();
    }

          4)session对数据库进行修改操作

         

/**
     * 对数据库进行修改操作
     */
    @Test
    public void fun4() {
        //1. 创建configuraion对象并加载配置文件
        Configuration conf = new Configuration().configure();
        
        //2. 创建sessionfactory工厂
        SessionFactory sf = conf.buildSessionFactory();
        
        //3. 打开一个新的session对象
        Session session = sf.openSession();
        
        //4. 开启事务并获得操作事务的对象
        Transaction tx = session.beginTransaction();
        
        //5. 对数据库进行删除操作
        //获得需要修改的对象
        Customer customer = session.get(Customer.class, 2l);
        customer.setCust_name("腾讯");
        //执行修改操作
        session.update(customer);
        
        //6. 提交事务
        tx.commit();
        
        //7. 释放资源
        session.close();
        sf.close();
    }

       4. Tracsaction

          hibernate内部封装了事务的操作,只需要调用方法即可

          1)打开事务

         方式一:

    //1. 获得事务
        Transaction tx = session.getTransaction();
        //2. 开启事务
        tx.begin();

         方式二(推荐):

      // 开启事务并获得操作事务的对象
        Transaction tx = session.beginTransaction();

          2)提交事务

            tx.commit();

          3)回滚事务

           tx.rollback();

原文地址:https://www.cnblogs.com/guodong-wang/p/7441560.html