Hibernate的学习笔记day01

  • 1.什么是HIbernate框架?
    Hibernate是一种ORM框架,全称为 Object Relative Mapping,是一个高性能的对象关系型持久化存储和查询的服务,不仅关注于从 Java 类到数据库表的映射,也有 Java 数据类型到 SQL 数据类型的映射,另外也提供了数据查询和检索服务。

  • 2.什么是框架?
    指的是软件的半成品,已经完成了部分功能。

  • 3 .为什么要学习Hibernate框架?

    • Hibernate对JDBC访问数据库的代码做了轻量级的封装,大大的简化了数据访问层繁琐的重复性代码,并且减少了内存消耗,加快了运行效率
    • Hibernate是一个基于JDBC的主流持久层框架,是一个优秀的ORM实现,它很大程度的简化了DAO(Data Access Object,数据访问对象)层编码工作。
    • Hibernate的性能非常好,映射的灵活性很出色,它支持很多关系型数据库,从一对一到多对多的各种复杂关系。
    • 可扩展性强,由于源代码的开放以及API的开放,当本身功能不够用时,可以自行编码进行扩展。
  • 4 . hibernate的优势

    • hibernate使用XML文件来处理映射Java类到数据库表格中,不用编写任何代码。
    • 在数据库中直接存储和检索Java对象提供简单的API
    • 如果数据库中或者其他任何表格出现变化,那么仅需要改变XML文件属性。
    • 抽象不熟悉的SQL类型,并为我们提供工作中所熟悉的java对象。
  • 5.相关概念

    1.持久化:将我们想要保存的数据保存到硬盘上,也就是我们电脑的磁盘上,为什么叫持久化呢,就是数据能够保存的很久,所以叫持久化,现在对持久化的实现过程大多通过各种关系型数据库完成,所以我们常说的,将数据保存到数据库中,其实是数据库帮我们帮数据保存到硬盘中了。

    持久层:把数据库看成是内存的一部分,我们就当做将数据保存到数据库中,就像保存到了硬盘中一样,所以在操作数据库的或者跟数据库打交道的那一层就是就持久层。

    ORM:Object Relational Mapping,对象关系映射,这个是一个思想,模型,或者说是规范。关系数据库中的记录映射成为程序语言中的对象实例,然后通过操作对象,来达到操作数据库的这样一种思想。如果没有ORM思想,我们之前就是直接操作数据库中的记录字段,来达到存储数据的目的。

    持久化类:持久化类就是可以将类保存到数据库中,并还可以从数据库中拿到该类,这就叫持久化类。

    持久化对象:持久化类的实例对象,能保存到数据库中,也能从数据库中取出来。

hibernate的入门

  • 1.下载Hibernate的开发环境
    http://www.hibernate.org/downloads

  • 2.解压目录介绍

    • documentation–>hibernate开发的文档
    • lib
      required–>开发的必须依赖包
      optional–>开发的可选的jar包
    • project–> 提供的项目包
    • Hibernate框架的入门(一)
  • 3.安装环境

创建一个Java项目,导入jar包

  1. 数据库驱动包
  2. hibernate开发的必须jar包
  3. hibernate的日志记录包
  • 4.创建数据库表
   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;

  • 5.创建实体类
package com.hibernate.demo1;
	    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;
		}
     	}
  • 6.创建映射

映射需要通过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.hibernate.demo1.Customer" table="cst_customer">
		<!-- 建立类中的属性与表中的主键对应 -->
		<id name="cust_id" column="cust_id">
			<generator class="native"></generator>
		</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>
  • 7.创建一个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:///hibernate01</property>
      		<property name="hibernate.connection.username">root</property>
      		<property name="hibernate.connection.password">123</property>
      		
      		<!-- 配置Hibernate的mysql方言 -->
      		<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>
      		<!--引入映射文件  -->
      		<mapping resource="com/hibernate/demo1/Customer.hbm.xml"></mapping>
      	</session-factory>
      </hibernate-configuration>
    
  • 8.编写测试代码

      package com.hibernate.demo1;
      
      import org.hibernate.Session;
      import org.hibernate.SessionFactory;
      import org.hibernate.Transaction;
      import org.hibernate.cfg.Configuration;
      import org.junit.Test;
      
      public class HibernateDemo1 {
      	@Test
      	public void demo1() {
      	//1.加载Hibernate的核心配置文件
      			Configuration configuration = new Configuration().configure();
      	//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("里斯本");
      			session.save(customer);
      	//6.事务提交
      			transaction.commit();
      	//7. 资源释放
      			session.close();
      	}
      }
    
  • 9.映射文件配置信息

    • class标签的配置

      • class标签用来建立类与表的映射关系
      • 属性:

      name : 类的全路径
      table : 表名(类名与表名一致,table可以省略)
      catalog : 数据库名

    • id标签的配置

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

      name : 类中的属性名
      column : 表中的字段名(类中的属性名和表中的字段名如果一致可省略)
      length : 长度
      type : 类型

      generator : 标签用来自动生成主键值
      1、increment:主键自动增长、由hibernate来管理
      注意:如果数据库也设置了自动增长,就会发生主键冲突问题
      2、identity:由底层数据库来管理生成,不由hibernate管理,也就是说底层数据库怎么设置的主键就怎么来
      注意:mysql、sql server可以,oracle不可以
      3、sequence:标识符生成器,就是底层数据库来管理生成,利用底层数据库提供的序列来生成标识符,不由hibernate管理
      注意:mysql不支持序列 oracle支持
      4、native:由底层数据库自己来决定使用什么策略,hibernate不管
      注意:mysql自动选择identity、oracle自动选择sequence
      5、uuid:随机生成32位不相同的字符串。

    • property标签的配置

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

      name : 类中的属性名
      column : 表中的字段名
      length : 长度
      type : 类型
      not-null : 设置非空
      unique : 设置唯一

  • 10.hibernate的核心配置

    • 配置方式有两种

      第一种文件名:hibernate.properties
      hibernate.connection.driver_class=com.mysql.jdbc.Driver
      hibernate.connection.url=jdbc:mysql:///hibernate
      hibernate.connection.username=root
      hibernate.connection.password=123
      属性配置文件不能引入映射文件,需要手动引入。

      第二种文件名:XML文件的方式
      文件名:hibernate.cfg.xml

    • 必须的配置

      • 连接数据库的基本参数

      驱动类 :com.mysql.jdbc.Driver
      url路径
      用户名
      密码
      数据库的方言

      • 可选的配置选项

      显示SQL : hibernate.show_sql
      格式化 :hibernate.format_sql

      自动建表 : hibernate.hbm2ddl.auto
      none : 不使用hibernate的自动建表
      create : 如果数据库中已经有表,删除原有的表,重新创建,如果没有,则新建表(用于测试)
      create-drop : 如果数据库已经有表,删除原有的表,执行操作,删除这个表,如果没有,则新建表,使用完毕后删除该表(用于测试)
      update : 如果数据库中有表,使用原有表,如果没有则创建(更新表结构)
      validate : 如果没有表,不会创建表,只有使用数据库原有的表(校验映射和表结构)。

    • 映射文件的映入

      引入映射文件的位置(路径换成斜杠)
      <mapping resource=“com/hibernate/demo1/Customer.hbm.xml”>

    1. hibernate的核心API详解
    • configuration

      Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。虽然Configuration 类在整个Hibernate 项目中只扮演着一个很小的角色,但它是启动hibernate 时所遇到的第一个对象。

      1.加载核心配置文件

      1. 如果是hibernate.properties文件
        Configuration cfg =new Configuration();
      2. 如果是hibernate.cfg.xml文件
        Configuration cfg =new Configuration().configure();

      2.加载映射文件
      手动加载
      configuration.addResource(“hibernate01/demo1/hibernate.hbm.xml”);

    • SessionFactory

      该接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。
      它是线程安全的,同一个实例可以被应用中的多个线程共享。
      内部维护连接池,配置C3P0,自定义工具类。

    • Session接口

      1.从SessionFactory中可以获得Session实例。
      2.Session接口是Hibernate应用中使用最广泛的接口,它是持久化管理器,提供添加、更新、删除、加载、查询对象。
      常用方法:
      save(Object obj)
      get()/load()
      update()
      delete()
      saveOrUpdate()
      3.Session不是线程安全的,所以应避免多个线程共享同一个Session实例。
      4. Session是轻量级对象,它的创建和销毁不需要太多资源,这意味着在应用中可以经常创建和销毁Session对象。
      5.Session有一个缓存,称之为Hibernate的一级缓存,它存放当前工作单元加载的持久化对象,每个Session都有自己的缓存,缓存中的对象只能被当前工作单元访问。

    • Transaction接口

      Transaction是Hibernate的数据库事务接口,它对底层事务接口进行了封装。
      开启事务:
      Transaction tx = session.beginTransaction();
      事务提交和回滚方法:
      tx.commit();
      tx.rollback();
      事务四个特性:原子性、一致性、隔离性、持久性

    • Query和Criteria接口
      这两个是Hibernate的查询接口,用于向数据库查询对象,以及控制执行查询的过程。

      1. Query实例包装了一个HQL(Hibernate Query Language)来查询。
      2. Criteria接口完全封装了基于字符串形式的查询语句,比Query更面向对象,Criteria更擅长执行动态查询。
  • hibernate中抽取工具类

      package hibernate.utils;
      import org.hibernate.Session;
      import org.hibernate.SessionFactory;
      import org.hibernate.cfg.Configuration;
      public class HibernateUtils {
      
      	public static final Configuration cfg;
      	public static final SessionFactory sf;
      
      	static {
      		cfg = new Configuration().configure();
      		sf = cfg.buildSessionFactory();
      	}
      
      	public static Session openSession() {
      		return sf.openSession();
      	}
      }
    
  • 配置C3P0

      <!--配置C3P0连接池  -->
      	<property name="connection.provider_class">org.hibernate.connection.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>
    
  • 代码块

      package com.hibernate.demo1;
      import java.io.Serializable;
      import java.util.Arrays;
      import java.util.List;
      import org.hibernate.SQLQuery;
      import org.hibernate.Session;
      import org.hibernate.Transaction;
      import org.junit.Test;
      import hibernate.utils.HibernateUtils;
      
      public class HibernateDemo2 {
      	@Test
      	public void demo1() {
      		// 添加信息方法
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		Customer customer = new Customer();
      		customer.setCust_name("王大大");
      		Serializable id = session.save(customer);
      		System.out.println(id);
      		tx.commit();
      		session.close();
      	}
      
      	@Test
      	// 查询:
      	// get方法和load方法的区别
      	public void demo2(){
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		/**
      		 * get方法
      		 * 	*采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
      		 *   查询后返回是真实对象本身。
      		 * 	*查询一个找不到的对象的时候,返回null
      		 * 
      		 * load方法
      		 * 	* 采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
      		 *  * 查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
      		 *  * 查询一个找不到的对象的时候,返回ObjectNotFoundException
      		 */
      		 
      		// 使用get方法查询 	// 发送SQL语句
      		Customer customer = session.get(Customer.class, 100l); 
      		System.out.println(customer);
      		
      		// 使用load方法查询
      		Customer customer = session.load(Customer.class, 200l);
      		System.out.println(customer);
      		
      		tx.commit();
      		session.close();
      	}
      	
      	@Test
      	// 修改操作
      	public void demo3(){
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		
      		// 直接创建对象,进行修改
      		Customer customer = new Customer();
      		customer.setCust_id(1l);
      		customer.setCust_name("王聪");
      		session.update(customer);
      		
      		// 先查询,再修改(推荐)
      		Customer customer = session.get(Customer.class, 1l);
      		customer.setCust_name("王小贱");
      		session.update(customer);
      		
      		tx.commit();
      		session.close();
      	}
      	
      	@Test
      	// 删除操作
      	public void demo4(){
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		
      		// 直接创建对象,删除
      	Customer customer = new Customer();
      		customer.setCust_id(1l);
      		session.delete(customer);
      		
      		// 先查询再删除(推荐)--级联删除
      		Customer customer = session.get(Customer.class, 2l);
      		session.delete(customer);
      		
      		tx.commit();
      		session.close();
      	}
      	
      	@Test
      	// 保存或更新
      	public void demo5(){
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		
      		Customer customer  = new Customer();
      		customer.setCust_name("王凤");
      		session.saveOrUpdate(customer);
      		
      		Customer customer = new Customer();
      		customer.setCust_id(3l);
      		customer.setCust_name("李如花");
      		session.saveOrUpdate(customer);
      		
      		tx.commit();
      		session.close();
      	}
      	
      	@Test
      	// 查询所有
      	public void demo6(){
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		
      		// 接收HQL:Hibernate Query Language 面向对象的查询语言
      		Query query = session.createQuery("from Customer");
      		List<Customer> list = query.list();
      		for (Customer customer : list) {
      			System.out.println(customer);
      		}
      		
      		// 接收SQL:
      		SQLQuery query = session.createSQLQuery("select * from cst_customer");
      		List<Object[]> list = query.list();
      		for (Object[] objects : list) {
      			System.out.println(Arrays.toString(objects));
      		}
      		tx.commit();
      		session.close();
      	}
      }
    

相关文章: