Hibernate_01

一、hibernate是什么

1.1、框架是什么

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

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

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

1.2hibernate框架是什么

1.3hibernate的好处

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

2、hibernate是一款orm框架(orm:object relationg mapping. 对象关系映射)

3、orm分4级:hibernate属于4级:完全面向对象操作数据库;mybatis属于2;dbutils属于1级

二、hibernate框架的搭建(快速入门)

所需要的文件:链接:https://pan.baidu.com/s/1bcPfAQ5znS0WSExSwcaDiw
提取码:vwa5

1、导包

Hibernate必要包:

数据库驱动包:

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

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_linkman` varchar(64) 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=94 DEFAULT CHARSET=utf8;

3、创建实体类【Customer.java】

package hibernate.hnu.domain;
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 + "]";
	}
	
	
	
}

4XML  DTD约束文档设置

打开这两个文件,将网址形式的东西黏贴到key里,注意key 上面改成URI

(这两个文件在链接中的dtd文件目录下)

5、创建xxx.hbm.xml文件和hibernate.cfg.xml文件

实体类目录下创建【customer.hbm.xml】

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="hibernate.hnu.domain.Customer" table="cst_customer">
		<id name="cust_id" column="cust_id">
			<generator class="native"></generator>
		</id>
		
		<property name="cust_name" column="cust_name"></property>
		<property name="cust_source" column="cust_source"></property>
		<property name="cust_industry" column="cust_industry"></property>
		<property name="cust_level" column="cust_level"></property>
		<property name="cust_linkman" column="cust_linkman"></property>
		<property name="cust_phone" column="cust_phone"></property>
		<property name="cust_mobile" column="cust_mobile"></property>
	
	
	</class>

</hibernate-mapping>

src目录下创建hibernate的配置文件【hibernate.cfg.xml】

去hibernate解压文件中找到project文件夹,进入etc文件夹,打开hibernate.properties文件。搜索找到mysql相关配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<!-- 搜 MySQL

#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password

 -->

<hibernate-configuration>
  <session-factory>
  	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  	<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
  	<property name="hibernate.connection.username">root</property>
  	<property name="hibernate.connection.password">123456</property>
  	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- 搜 show

#hibernate.show_sql true
#hibernate.format_sql true
 -->
	<property name="hibernate.show_sql">true</property>
	<property name="hibernate.format_sql">true</property>

<!-- 搜 hbm

#hibernate.hbm2ddl.auto create-drop
#hibernate.hbm2ddl.auto create
#hibernate.hbm2ddl.auto update
#hibernate.hbm2ddl.auto validate -->
	<property name="hibernate.hbm2ddl.auto">update</property>
	
<!-- 

resource是刚刚配置的.hbm.xml的完整路径:
/hibernate/src/cn/itcast/domain/Customer.hbm.xml 
去掉src以前的部分 
-->
	
	<mapping resource="hibernate/hnu/domain/Customer.hbm.xml"/>

  </session-factory>
</hibernate-configuration>

6、测试

最终的文件层次:

package hibernate.hnu.test;

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

import hibernate.hnu.domain.Customer;

public class HibernateTest {

	@Test
	public void fun(){
		Configuration configure = new Configuration().configure();
		
		SessionFactory sessionFactory = configure.buildSessionFactory();
		
		Session session = sessionFactory.openSession();
		
		Transaction transaction = session.beginTransaction();
		
		Customer customer = new Customer();
		
		
		customer.setCust_name("湖南大学研究生院");
		
		session.save(customer);
		
		transaction.commit();
		
		session.close();
		
		sessionFactory.close();
	}
}

三、hibernate配置文件详解

1orm元数据(位于实体类同目录下,命名:xxx.hbm.xml

1.1、根元素

1.2class元素

1.3id元素

1.4property元素

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >

<!-- 配置表与实体对象的关系 -->
<!-- package属性:填写一个包名,在元素内部凡是需要写完整类名的属性,可以直接简写类名 -->

<hibernate-mapping package="hibernate.hnu.domain">
	
	<!-- class元素:配置实体与表的对应关系
			name:完整类名
			table:数据库表名
	 -->
	<class name="hibernate.hnu.domain.Customer" table="cst_customer">
		
		<!-- id元素: 
				name:填写属性名
				column(可选):填写列名	
				type(可选):填写列(属性)的类型	,hibernate会自动检测实体的属性类型
					每个类型有三种类型:java类型|hibernate类型|数据库类型
		 		not-null(可选):配置该属性(列)是否能为空,默认值:false 
		 		length(可选):配置数据库中列的长度,默认值:使用数据库类型的最大长度。
		 -->
		<id name="cust_id" column="cust_id">
			
			<!--generator;主键生成策略  -->
			<generator class="native"></generator>
		</id>
		
		<!-- property元素:配置主键映射的属性
				name:填写主键对应的属性名
				column(可选):填写主键对应的列名,默认值:列名会默认使用属性名
				type(可选):填写列(属性)的类型	,hibernate会自动检测实体的属性类型
					每个类型有三种类型:java类型|hibernate类型|数据库类型
		 		not-null(可选):配置该属性(列)是否能为空,默认值:false 
		 		length(可选):配置数据库中列的长度,默认值:使用数据库类型的最大长度。
		 -->
		<property name="cust_name" column="cust_name"></property>
		<property name="cust_source" column="cust_source"></property>
		<property name="cust_industry" column="cust_industry"></property>
		<property name="cust_level" column="cust_level"></property>
		<property name="cust_linkman" column="cust_linkman"></property>
		<property name="cust_phone" column="cust_phone"></property>
		<property name="cust_mobile" column="cust_mobile"></property>
	
	
	</class>

</hibernate-mapping>

2hibernate主配置(位于src目录下,命名:xxx.cfg.xml)

2.1、必选属性配置(5)

2.2、可选属性配置(3)

2.3、元数据引入配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >

<hibernate-configuration>

<!-- hibernate.properties文件中搜索配置信息 -->
<!-- 5个必选配置 -->
<!-- 搜 MySQL

#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password

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

 <!-- 3个可选配置 -->
 <!-- 搜show
 #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>
  
 <!--搜hbm
## 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>


	
<!-- 引入orm元数据
  		填写src下的路径
 -->
<!-- resource是刚刚配置的Customer.hbm.xml的完整路径:
/javaFrame/src/hibernate/hnu/domain/Customer.hbm.xml
去掉src以前的部分 -->
	<mapping resource="hibernate/hnu/domain/Customer.hbm.xml"/>

  </session-factory>
</hibernate-configuration>

四、hibernateAPI详解

package hibernate.hnu.test;

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

import hibernate.hnu.domain.Customer;

public class HibernateTest {

	@Test
	public void fun(){
		
		/***************************************************
		 Configuration功能:配置加载类,用于加载主配置,orm元数据加载
		 *******************************************/		
		//1、创建,调用空参构造
		Configuration configure = new Configuration();
		
		//2、读取指定配置文件,空参加载方法,默认读取src目录下的hibernate.cfg.xml文件
		configure.configure();
		
		
		/**********************************************************
		SessionFactory功能: 用于创建操作数据库核心对象session对象的工厂
		 简单功能就一个-----创建session对象
		注意:
		(a)、sessionfactory负责保存和使用所有的配置信息,所以它消耗内存资源非常大
		(b)、sessionfactory属于线程安全的设计

		结论:保证在web项目中只创建一个SessionFactory
        **************************************************/		
		//3、根据配置信息,创建SessionFactory对象
		SessionFactory sessionFactory = configure.buildSessionFactory();
		
		
		/*****************************************************
		Session功能: 表达hibernate框架与数据库之间的连接(会话)
                                                 类似于JDBC时候的Connection对象。还可以完成对数据库的增删改查操作
                       session是hibernate操作数据库的核心对象
        ************************************************************/
		//4.1、打开一个新的session对象
		Session session = sessionFactory.openSession();
		//4.2、获得一个与线程绑定的session
		//Session currentSession = sessionFactory.getCurrentSession();
		

		//5、session获得操作事务的Transaction对象
	    //获得操作事务的tx对象
		Transaction tx = session.getTransaction();
		
		//开启事务并获得操作事务的transaction对象(建议使用)
		Transaction transaction = session.beginTransaction();
		
		//------------------------------------------
		Customer customer = new Customer();
		customer.setCust_name("湖南大学研究生院");
		session.save(customer);
		//--------------------------------------------
		
		
		//提交事务
		transaction.commit();
		//回滚事务
		//transaction.rollback();
		
		//释放资源
		session.close();
		
		sessionFactory.close();
	}
}

4.1、利用hibernate添加数据

package hibernate.hnu.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import hibernate.hnu.domain.Customer;

public class HibernateTest {

	@Test
	public void fun(){
		
		//1、创建,调用空参构造
		Configuration configure = new Configuration();
		
		//2、读取指定配置文件,空参加载方法,默认读取src目录下的hibernate.cfg.xml文件
		configure.configure();
		
		//3、根据配置信息,创建SessionFactory对象
		SessionFactory sessionFactory = configure.buildSessionFactory();
		
		//4、打开一个新的session对象
		Session session = sessionFactory.openSession();

		//5、session开启事务并获得操作事务的transaction对象
		Transaction transaction = session.beginTransaction();
		
		
		//--------------------修改这里添加数据----------------------
		Customer customer = new Customer();
		customer.setCust_name("湖南大学研究生院");
		session.save(customer);
		//--------------------------------------------
		
		
		
		//提交事务
		transaction.commit();
		//回滚事务
		//transaction.rollback();
		
		//释放资源
		session.close();
		sessionFactory.close();
	}
}

【查看数据库】

4.2、利用hibernate获取数据

package hibernate.hnu.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import hibernate.hnu.domain.Customer;

public class HibernateTest {

	@Test
	public void fun(){
		
		//1、创建,调用空参构造
		Configuration configure = new Configuration();
		
		//2、读取指定配置文件,空参加载方法,默认读取src目录下的hibernate.cfg.xml文件
		configure.configure();
		
		//3、根据配置信息,创建SessionFactory对象
		SessionFactory sessionFactory = configure.buildSessionFactory();
		
		//4、打开一个新的session对象
		Session session = sessionFactory.openSession();

		//5、session开启事务并获得操作事务的transaction对象
		Transaction transaction = session.beginTransaction();
		
		
		//--------------------修改这里修改程序----------------------
		Customer c = session.get(Customer.class, 1L);
		
		//注意我在Customer类中重写了toString方法
		System.out.println(c);
		
		//--------------------------------------------
		
		//提交事务
		transaction.commit();
		//回滚事务
		//transaction.rollback();
		
		//释放资源
		session.close();
		sessionFactory.close();
	}
}

【控制台】

4.3、利用hibernate修改数据库中的数据

package hibernate.hnu.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import hibernate.hnu.domain.Customer;

public class HibernateTest {

	@Test
	public void fun(){
		
		//1、创建,调用空参构造
		Configuration configure = new Configuration();
		
		//2、读取指定配置文件,空参加载方法,默认读取src目录下的hibernate.cfg.xml文件
		configure.configure();
		
		//3、根据配置信息,创建SessionFactory对象
		SessionFactory sessionFactory = configure.buildSessionFactory();
		
		//4、打开一个新的session对象
		Session session = sessionFactory.openSession();

		//5、session开启事务并获得操作事务的transaction对象
		Transaction transaction = session.beginTransaction();
		
		
		//--------------------修改这里修改数据----------------------
		
		//6.1、获取要修改的对象
		Customer c = session.get(Customer.class, 1L);
		
		//6.2、修改
		c.setCust_name("中国科学技术大学");
		
		//6.3、执行update
		session.update(c);
		
		//--------------------------------------------
		
		//提交事务
		transaction.commit();
		//回滚事务
		//transaction.rollback();
		
		//释放资源
		session.close();
		sessionFactory.close();
	}
}

【数据库变化】

中南大学研究生院 ------中国科学技术大学

4.4、利用hibernate删除数据库中的数据

package hibernate.hnu.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import hibernate.hnu.domain.Customer;

public class HibernateTest {

	@Test
	public void fun(){
		
		//1、创建,调用空参构造
		Configuration configure = new Configuration();
		
		//2、读取指定配置文件,空参加载方法,默认读取src目录下的hibernate.cfg.xml文件
		configure.configure();
		
		//3、根据配置信息,创建SessionFactory对象
		SessionFactory sessionFactory = configure.buildSessionFactory();
		
		//4、打开一个新的session对象
		Session session = sessionFactory.openSession();

		//5、session开启事务并获得操作事务的transaction对象
		Transaction transaction = session.beginTransaction();
		
		
		//--------------------修改这里修改程序----------------------
		
		//6.1、获取要删除的对象
		Customer c = session.get(Customer.class, 1L);
		
		//6.2、执行delete
		session.delete(c);
		
		//--------------------------------------------
		
		//提交事务
		transaction.commit();
		//回滚事务
		//transaction.rollback();
		
		//释放资源
		session.close();
		sessionFactory.close();
	}
}

【数据库变化】

发现只有"湖南大学研究生院"了

猜你喜欢

转载自blog.csdn.net/weixin_39464426/article/details/89243465
今日推荐