Hibernate

 01 什么是Hibernate?  百度百科解释

 总结:持久层的ORM框架    ORM (Object Relational Mapping)-对象关系映射

02 什么是对象关系映射?

 ORM 是利用描述对象和数据库表之间映射的元数据,自动化把Java应用程序中的对象,持久化到关系型数据库表中.通过操作Java对象,就可以完成对数据库表的操作.

 03 为什么学习Hibernate?

04 Hibernate5的使用(以eclipse环境搭建)

  1. hibernate 开发环境下载   --解压

 2. 创建项目,引入jar包,

3.mysql数据库中创建表

CREATE TABLE `emp` (
  `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;

4.创建数据表的实体类Emp.Java,添加getter和setter方法

package com.itheima.Entity;

public class Emp {
	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 + "]";
	}
}

5.创建数据表与实体类的映射文件Emp.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		:类的全路径
	table		:表名(类名与表名一致,table可以省略)
	catalog		:数据库名

	【id标签的配置】
	标签用来建立类中的属性与表中的主键的对应关系
	属性:
	name		:类中的属性名
	column		:表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
	length		:长度
	type		:类型

	【property标签的配置】
	标签用来建立类中的普通属性与表的字段的对应关系
	属性:
	name		:类中的属性名
	column		:表中的字段名
	length		:长度
	type		:类型
	not-null	:设置非空
	unique		:设置唯一
	 -->
	
	<!-- 建立类与表的映射 -->
	<class name="com.itheima.Entity.Emp" table="emp" catalog="eesy">
		
		<!-- 建立类中的属性与表中的主键对应 -->
		<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>

6.创建核心配置文件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>

<!--
包含三部分
1.必须的配置
	连接数据库的基本的参数
	驱动类
	url路径
	用户名
	密码
	方言
2.可选的配置
	显示SQL		:hibernate.show_sql
	格式化SQL	:hibernate.format_sql
	自动建表	       :hibernate.hbm2ddl.auto
	     none       :不使用hibernate的自动建表
	     create		:如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
	     create-drop:如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
	     update		:如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
	     validate	:如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
3.映射文件的引入	
	引入映射文件的位置
    <mapping resource="com/itheima/Entity/Emp.hbm.xml"/>
 -->
	<session-factory>
	<!-- jdbc驱动 -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <!-- 数据库地址-->
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/eesy</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="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>
		<!-- 映射文件配置 -->
		<mapping resource="com/itheima/Entity/Emp.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

7.编写并运行测试类

package com.itheima.Entity;

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

public class Hibernate1 {
	@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.编写代码
		Emp emp = new Emp();
		emp.setCust_name("二哈");
		session.save(emp);
		// 6.事务提交
		transaction.commit();
		// 7.资源释放
		session.close();
		sessionFactory.close();
	}

}

  运行结果:

 ---------------运行结束-----------------

1.编写测试类hibernateUtiis.java,每次写测试类都需要加载核心配置文件,以及创建SessionFactory对象.代码冗余.

package untils;
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();
	}
}

 2.编写新的测试类执行CRUD操作

package com.itheima.Entity;
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 untils.HibernateUtils;
public class Hibernate2 {
	@Test
	// 保存客户
	public void demo1(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		Emp emp  = new Emp();
		emp.setCust_name("狗狗哲");
		// 返回保存信息的ID
		Serializable id = session.save(emp);
		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方法查询
		/*Customer emp = session.get(Emp.class, 1L); // 发送SQL语句
		System.out.println(emp);*/
		
		// 使用load方法查询
		Emp emp = session.load(Emp.class, 1L);
		System.out.println(emp);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// 修改操作
	public void demo3(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		// 直接创建对象,进行修改
		/*Emp emp = new Emp();
		customer.setCust_id(1l);
		customer.setCust_name("王聪");
		session.update(customer);*/
		
		// 先查询,再修改(推荐)
		Emp emp = session.get(Emp.class, 10l);
		emp.setCust_name("帅帅");
		session.update(emp);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// 删除操作
	public void demo4(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		// 直接创建对象,删除
	/*	Emp emp = new Emp();
		emp.setCust_id(1l);
		session.delete(emp);*/
		
		// 先查询再删除(推荐)--级联删除
		Emp emp = session.get(Emp.class, 5L);
		session.delete(emp);
		 
		tx.commit();
		session.close();
	}
	
	@Test
	// 保存或更新
	public void demo5(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		Emp emp = new Emp();
		emp.setCust_id(7l);
		emp.setCust_name("沙拉");
		session.saveOrUpdate(emp);
		
		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 Emp");
		List<Emp> list = query.list();
		for (Emp emp : list) {
			System.out.println(emp);
		}*/
		
		// 接收SQL:
		SQLQuery query = session.createSQLQuery("select * from emp");
		List<Object[]> list = query.list();
		for (Object[] objects : list) {
			System.out.println(Arrays.toString(objects));
		}
		tx.commit();
		session.close();
	}
}

05 Hibernate的API

1.Configuration:配置对象

总结:

 加载hibernate核心配置文件

  *如果hibernate核心配置文件为properties类型 即 hibernate.properties
   Configuration configuration = new Configuration(); 
 
  *如果hibernate核心配置文件为pxml类型 即 hibernate.xml
	Configuration configuration = new Configuration().configure();

 加载数据表与实体类的映射文件(前提是hibernate核心配置文件种没有引入映射文件)

 // 手动加载映射
configuration.addResource("entity/Emp.hbm.xml");

  2.SessionFactory:Session工厂,类似于数据库连接池,用来创建session对象

 3.Session:连接对象

 总结:

    是hibernate与 数据库连接的桥梁,执行CRUD操作 ,方法如下

*save 保存方法
// 保存对象并返回保存信息的ID
Serializable id = session.save(emp);


*get与load 查询
get方法
		 * 	 采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
		 *   查询后返回是真实对象本身。
		 * 	 查询一个找不到的对象的时候,返回null
		 * 
load方法
		 * 	采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
		 *  查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
		 *  查询一个找不到的对象的时候,返回ObjectNotFoundException



*update 更新 ---应该先查询在更新
session.update(emp);

delete 删除  ---应该先查询在删除
//查询
Emp emp = session.get(Emp.class, 5L);
//删除
session.delete(emp);


*saveOrUpdate  --保存或者更新
 session.saveOrUpdate(emp);

*查询所有
createQuery
createSQLQuery

// 接收HQL:Hibernate Query Language 面向对象的查询语言
		/*Query query = session.createQuery("from Emp");
		List<Emp> list = query.list();
		for (Emp emp : list) {
			System.out.println(emp);
		}*/
		
// 接收SQL:
		SQLQuery query = session.createSQLQuery("select * from emp");
		List<Object[]> list = query.list();
		for (Object[] objects : list) {
			System.out.println(Arrays.toString(objects));
		}

4.Transaction:hibernate中的事务管理对象

Transaction tx = session.beginTransaction();
tx.commit()  --提交
tx.rollback() -- 回滚

Hibernate:持久层的ORM框架   ,你造了吗?___欢迎指正!

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值