Hibernate(一)之入门及常见配置

Hibernate的框架的概述

什么是框架?
框架:指的是软件的半成品,已经完成了部分功能。
EE的三层架构
在这里插入图片描述
什么是Hibernate?
在这里插入图片描述
Hibernate:Hibernate是一个持久层的ORM框架。
什么是ORM?
ORM:Object Relational Mapping(对象关系映射)。指的是将一个Java中的对象与关系型数据库中的表建立一种映射关系,从而操作对象就可以操作数据库中的表。
在这里插入图片描述
在这里插入图片描述

Hibernate的入门

1.下载Hibernate的开发环境
Hibernate3.x Hibernate4.x Hibernate5.x
https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/

2.解压Hibernate
在这里插入图片描述

documentation		:Hibernate开发的文档
lib					:Hibernate开发包
required			:Hibernate开发的必须的依赖包
optional			:Hibernate开发的可选的jar包
project				:Hibernate提供的项目

3.创建一个项目,引入jar包

数据库驱动包
Hibernate开发的必须的jar包
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.wangshi.hibername.demo01;

/**客户实体类
 * @author wanghaichaun
 *
 */
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 Customer() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Customer(Long cust_id, String cust_name, String cust_source, String cust_industry, String cust_level,
			String cust_phone, String cust_mobile) {
		super();
		this.cust_id = cust_id;
		this.cust_name = cust_name;
		this.cust_source = cust_source;
		this.cust_industry = cust_industry;
		this.cust_level = cust_level;
		this.cust_phone = cust_phone;
		this.cust_mobile = cust_mobile;
	}
	
	//get Set
	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;
	}
	//tosString
	@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 + "]";
	}
}

6.创建映射(*****)
映射需要通过XML的配置文件来完成,这个配置文件可以任意命名。
尽量统一命名规范(类名.hbm.xml)

<?xml version="1.0" encoding="UTF-8"?>
	
		<!-- hibernate的关系映射约束 -->
<!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="com.wangshi.hibername.demo01.Customer"  table="cst_customer" >
			
			<!-- 这里是  建立类中的属性与表中的主键对应
			属性:name:类中的属性名  column:表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
			length:长度    type:类型
			 -->
			<id name="cust_id"  column="cust_id">
					<!-- 生成主键的策略 increment  identity sequence native uuid assigned foreign-->
					<generator class="native" />
			</id>
			
			<!-- 建立类中的普通的属性和表的字段的对应
			name:类中的属性名  column:表中的字段名  length:长度  type:类型
			not-null:设置非空    unique:设置唯一
			 -->
			<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的核心配置文件的名称:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- hibernate核心配置约束 -->
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

		<!-- 必须的配置  下载的项目中etc找================ -->
	<session-factory>
		<!-- 连接数据库的基本参数   驱动类  url路径   用户名   密码-->
		<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">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>
		<!-- 自动创建表
		 none		:不使用hibernate的自动建表
		 create		:如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
		 create-drop	:如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
		*update		:如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
		*validate		:如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
		 -->
		<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/wangshi/hibername/demo01/Customer.hbm.xml "/>
	</session-factory>
</hibernate-configuration>

8.编写测试代码(*****)

package com.wangshi.hibername.demo01;



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

/**编写测试代码
 * @author wanghaichaun
 *			hibernate的入门
 */
public class HibernameDemo {
	
	//保存客户的案例
	@Test
	public void demo01() {
		
		//1.加载hibernate的核心配置
		Configuration configuration = new Configuration().configure();
		//手动加载映射文件
		//configuration.addResource("com/wangshi/hibername/demo01/Customer.hbm.xml");
		
		//2.创建一个SessionFactory对象:类似于JDBC中的连接池
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//3.通过SessionFactory获取到Session对象:类似于JDBC中的Connertion;
		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();
	}

}

Hibernate的常见配置

1.配置XML提示问题
在这里插入图片描述
在这里插入图片描述

Hibernate的映射的配置

1.映射的配置
【class标签的配置】
标签用来建立类与表的映射关系

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

【id标签的配置】
标签用来建立类中的属性与表中的主键的对应关系

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

【property标签的配置】
标签用来建立类中的普通属性与表的字段的对应关系

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

2.Hibernate的核心的配置
Hibernate的核心配置方式(了解)

一种方式:属性文件的方式    hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver
…
hibernate.show_sql=true
属性文件的方式不能引入映射文件(手动编写代码加载映射文件)
//手动加载映射文件
//configuration.addResource("com/wangshi/hibername/demo01/Customer.hbm.xml");


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

3.核心的配置
必须的配置

连接数据库的基本的参数
驱动类url路径用户名密码
方言

可选的配置

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

映射文件的引入
引入映射文件的位置

<mapping resource="com/wangshi/hibername/demo01/Customer.hbm.xml "/>
Hibernate的核心API

1.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");

2.SessionFactory:Session工厂
在这里插入图片描述
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存,是线程安全的对象。一个项目创建一个对象即可。
配置连接池:(了解)

		<!-- 配置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.wangshi.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**hibernate的工具类
 * @author wanghiachaun
 */

public class HibernateUtils {
	
	public static final Configuration cfg;
	public static final SessionFactory sf;
	
	/**静态代码块
	 * 加载hibernate的核心配置
	 * 创建一个SessionFactory对象
	 * @author wanghiachaun
	 */
	static{
		cfg = new Configuration().configure();
		sf = cfg.buildSessionFactory();
	}
	
	/**
	 * 获取当前线程绑定的会话
	 * getcurrentSession
 */
	public static Session getCurrentSession(){
		return sf.getCurrentSession();
	}
	
	/**建立连接
	 * @author wanghiachaun
	 */
	public static Session openSession() {
		return sf.openSession();
	}

}

3.Session:类似Connection对象是连接对象
在这里插入图片描述
Session代表的是Hibernate与数据库的链接对象。不是线程安全的。与数据库交互桥梁。

Session中的API
保存方法:
Serializable save(Object obj);

修改方法
void update(Object obj);

删除方法
void delete(Object obj);

保存或更新
void saveOrUpdate(Object obj)

查询方法:
T get(Class c,Serializable id);
T load(Class c,Serializable id);

get方法和load方法的区别?

	//查询 get load 区别
	/**
	 * get方法
	 * 	* 采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
	 *  * 查询后返回是真实对象本身。
	 * 	* 查询一个找不到的对象的时候,返回null
	 * 
	 * load方法
	 * 	* 采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
	 *  * 查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
	 *  * 查询一个找不到的对象的时候,返回ObjectNotFoundException
	 */
	@Test
	public void demo02(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		//get
		Customer customer = session.get(Customer.class,3l);
		System.out.println("get查询到customer="+customer);
		
		//load
		/*Customer customer = session.load(Customer.class, 1l);
		System.out.println("Load 查询到customer="+customer);*/
		
		tx.commit();
		session.close();
	}
	//保存客户 Serializable save(Object obj);
	@Test
	public void demo1() {
		//获取Session
		Session session = HibernateUtils.openSession();
		//开启事务
		Transaction tx = session.beginTransaction();
		//编写代码  保存
		Customer customer = new Customer();
		 customer.setCust_name("半仙");
		 Serializable id = session.save(customer);
		System.out.println("id="+id);
		
		//提交事务
		tx.commit();
		//资源释放
		session.close();

	}	
//修改void update(Object obj); 两种方式
		@Test
		public void demo03(){
			Session session = HibernateUtils.openSession();
			Transaction tx = session.beginTransaction();
			
			//编写修改代码[两种方式] 直接创建对象,进行修改
			/*Customer customer = new Customer();
			customer.setCust_id(2l);
			customer.setCust_name("王上仙");
			session.update(customer);
			System.out.println("创建对象修改="+customer);*/
			
			//先查询在修改(推荐)
			Customer customer = session.get(Customer.class, 1l);
			customer.setCust_name("上神");
			session.update(customer);
			System.out.println("先查再改="+customer);
			
			tx.commit();
			session.close();
			
		}
	
	
		//删除void delete(Object obj); 两种方式
		@Test
		public void demo04(){
			Session session = HibernateUtils.openSession();
			Transaction tx = session.beginTransaction();
			//编写删除代码  创建对象再删   
		/*	Customer customer = new Customer();
			customer.setCust_id(4l);
			session.delete(customer);*/
			
			//先查再删
			Customer customer = session.get(Customer.class,5l);
			session.delete(customer);
			System.out.println("先查再删="+customer);
			
			tx.commit();
			session.close();
		}
		
		//更新或保存
		@Test
		public void demo05(){
			Session session = HibernateUtils.openSession();
			Transaction tx = session.beginTransaction();
			
			//没有id是保存
			/*Customer customer = new Customer();
			customer.setCust_name("上等神仙");
			session.saveOrUpdate(customer);
			*/
			
			//有id是更新
			Customer customer = new Customer();
			customer.setCust_id(6l);
			customer.setCust_name("上等");
			session.saveOrUpdate(customer);
			System.out.println("customer="+customer);
			tx.commit();
			session.close();
		}
		
		//查询所有
		@Test
		public void demo06(){
			Session session = HibernateUtils.openSession();
			Transaction tx = session.beginTransaction();
			/*//接收HQL:Hibernate Query Language 面向对象的查询语言
			Query HQL = session.createQuery("from Customer");
			List <Customer>list = HQL.list();
			for (Customer customer : list) {
				System.out.println("查询所有="+customer);
			}*/
			
			Query query = session.createSQLQuery("select * from cst_customer");
			List<Object[]> list = query.list();
			for (Object[] objects : list) {
				System.out.println("obj"+Arrays.toString(objects));
			}
			
			tx.commit();
			session.close();
		}

4.Transaction:事务对象,Hibernate中管理事务的对象。
commit();
rollback();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值