Hibernate框架学习一

    最近呢博主一直忙于期末考试,所以一直没有更,今天刚刚看了一点hibernate框架的东西,所以就跟大家分享分享,虽然hibernate框架现在已经没人用了,但是个人一直觉得了解一下总比不知道好的多,博主也在其中学到很多新的东西,好了,闲话不多说了,咱们就开始吧(不喜勿喷)。

    一:Hibernate概述          

  1.1 什么是Hibernate

      Hibernate框架是当今(搞笑)主流的Java持久层框架之一,它是一个开放源代码的ORM(Object Relational Mapping,对象关系映射)框架,它对jdbc进行了轻量级的对象封装,使得Java开发人员可以使用面向对象的编程思想来操作数据库(现在都不用这个了,必然有其原因)

  1.2  为什么要学习 Hibernate

      使用传统的 JDBC 开发应用系统时, 如果是小型应用系统, 并不觉得有什么麻烦, 但是对千大型应用系统的开发, 使用 JDBC 就会显得力不从心。 例如对几十、 几百张包含几十个字段的表进行插入操作时, 编写的 SQL 语句不但很长, 而且繁琐, 容易出错;在读取数据时, 需要写多条 getXxx语句从结果集中取出各个字段的信息, 不但枯燥重复, 并且工作量非常大。 为了提高数据访问层的编程效率, GavinKing开发出了 个当今最流行的的ORM框架, 它就是Hibernate框架。
       所谓的ORM就是利用描述对象和数据库表之间映射的元数据,自动把Java应用程序中的对象,待久化到关系型数据库的表中。 通过操作Java对象, 就可以完成对数据库表的操作。 可以把ORM理解为关系型数据和对象的 个纽带,开发人员只需要关注纽带 端映射的对象即可。ORM原理如下

   1.3:框架是什么

        1.框架是用来提高开发效率的
        2.封装了好了一些功能.我们需要使用这些功能时,调用即可.不需要再手动实现.
        3.所以框架可以理解成是一个半成品的项目.只要懂得如何驾驭这些功能即可.

   1.4:  通俗的说hibernate框架是什么?

    ·     

      1.5:好处(通俗讲):操作数据库的时候,可以以面向对象的方式来完成.需要书写SQL语句(好不好)

      二:下载:

                 Hibernate下载地址 
                

      1.1详解:

            

 

               

                 

    三:Hibernate框架搭建

        1:导包
            Hibernate中lib包下的require文件夹里面的所有jar包导入

                

                外加一个驱动包

        2:创建数据库,准备表,实体(这里大家可能会不明白,但先不要着急,跟着博主做就行)

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`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

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

                3.1:写实体类(普通javabean):       

package yp.itcast.domain;

public class Customer {
	
	/*
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`)
) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;
	 */
	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.2:导入dtd约束(重要,可以不用,但是不利于写配置文件)

                    位置:下面的这个文件,导入xml的约束中(自己百度,挺好导入的);

              3.3:写实体的配置文件(orm元数据)

                    目前我们已经写好了实体对象(即前面的JavaBean对象),那么我们知道。hibernate框架是一套基于实体映射的框架,所以要想让实体具有映射的功能,我们必须去给它写一个配置文件(即映射文件)

                    注意:表的名字必须是:类名.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">
	<!-- 配置表与实体对象的关系 -->
	<!-- package属性:填写一个包名,在元素内部凡是需要书写完整类名的属性,可以直接简单类名了 -->
<hibernate-mapping package="yp.itcast.domain">
	<!-- 
		class元素:配置实体与表的对应关系的
			name:完整类名
			table:数据库表名
	 -->
	
	<class name="Customer" table="cst_customer">
		<!-- id:配置主键映射的属性
				name:填写主键对应的属性名
				column(可选):填写表中的主键列名。默认值:列名会默认使用属性名
				length(可选):配置数据库中列的长度,默认值:使用数据库类型的最大长度
		 -->
		<id name="cust_id" column="cust_id">
			<!-- generator:主键生成策略 -->
			<generator class="native"></generator>
		</id>
		
		<!-- property元素:除id之外的普通属性映射 
				name:填写属性名
				column(可选):填写表中列名
				type(可选):填写列(属性)的类型。如果不填,hibernate会自动检测实体的属性类型
						每个类型有三种填法:Java类型/hibernate类型/数据库类型
							Java:type="java.lang.String"
							hibernate:type="string"
							数据库类型:
								<property name="cust_name" column="cust_name">
									<column name="cust_name" sql-type="varchar"></column>
								</property>
							建议不填
				not-null(可选):配置该属性(列)是否不能为空。默认值:false
				length(可选):配置数据库中列的长度,默认值:使用数据库类型的最大长度
		-->
		<property name="cust_name" column="cust_name">
			<!-- <column name="cust_name" sql-type="varchar"></column> -->
		</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>

        4:书写主配置文件(??)

                  很多人就懵了,还要写啥啊,你忘了,hibernate框架是优化Dao层的开发的,Dao是跟数据库打交道的,肯定要写跟数据库的配置相关的啊。

                  注意:文件必须放在src目录下(因为其加载文件的源码中路径是src下的路径);文件名: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>
		<!-- 
			#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
		
		 -->
		 <!-- 数据库驱动 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		 <!-- 数据库url -->
		<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
		 <!-- 数据库连接用户名 -->
		<property name="hibernate.connection.username">root</property>
		 <!-- 数据库连接密码 -->
		<property name="hibernate.connection.password">root</property>
		 <!-- 数据库方言
		 		不同的数据库中,sql语法略有区别,指定方言可以让hibernate框架生成sql语句时,针对数据库的方言生成
		 		sql99标准:
		 				DDL:定义语言(库表的增删改查)
		 				DML:操纵语言(增删改查)
		 				DCL:控制语言(事务 权限)
		 		
		 		注意:MySQL在选择方言时,请选择最短的方言。
		  -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<!-- 
			#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>	
		
		<!-- 引入orm元数据
				路径书写:填写src下的路径
		
		 -->
		<mapping resource="yp/itcast/domain/Customer.hbm.xml.xml"/>		
	</session-factory>

</hibernate-configuration>

       5:书写代码测试:

package yp.itcast.test;

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

import yp.itcast.domain.Customer;

//测试hibernate框架
public class Demo {
	
	@Test
	//保存客户操作
	public void fun1(){
		Configuration conf = new Configuration().configure();
		
		SessionFactory sessionFactory = conf.buildSessionFactory();
	
		Session session = sessionFactory.openSession();
	
		Transaction tx = session.beginTransaction();
		//------------------------------------------
		Customer c = new Customer();
		c.setCust_name("公司");
		
		session.save(c);//执行保存
		
		//------------------------------------------
		tx.commit();
		
		session.close();
		
		sessionFactory.close();
		
		
	}
	
}
    四:HibernateAPI详解:
             一:Configuration对象:
                   1:Configuration功能:配置加载类,用于加载主配置,orm元数据加载
                   2:创建,调用空参构造
                Configuration conf = new Configuration();
                   3:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
                conf.configure();
                   4:根据配置信息,创建SessionFactory对象;
                SessionFactory sf = conf.buildSessionFactory();
             二:SessionFactory对象:
                 1:SessionFactory功能:用于创建操作数据库核心对象session对象的工厂; 简单说功能就一个------创建session对象;
               注意:1:sessionfactory 负责保存和使用所有配置信息,消耗内存资源非常大
                         2:sessionfactory属于线程安全的对象设计(不是synchronized)
                    结论:保证web项目中,只创建一个sessionfactory

                 2:根据配置信息,创建SessionFactory对象;

	        SessionFactory sf = conf.buildSessionFactory();
                   3:获得session(打开一个新的session对象)
                sf.openSession();
                       获得一个与线程绑定的session对象(明天讲解
                sf.getCurrentSession();
              三:Session对象:               
                    1:Session(翻译:会话(一次会话,一次链接(web服务器,邮件服务器)))功能:表达hibernate框架与数据库之间的连接(会话)。
                        session类似于JDBC年代的connection对象,还可以完成对数据库中数据的增删改查操作
                        session是hibernate操作数据库的核心对象
                        (看我的代码注释,详细着呢)
package yp.itcast.b_api;

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

import yp.itcast.domain.Customer;

//学习Session对象
// Session(翻译:会话(一次会话,一次链接(web服务器,邮件服务器)))功能:表达hibernate框架与数据库之间的连接(会话)。
//			session类似于JDBC年代的connection对象,还可以完成对数据库中数据的增删改查操作
//			session是hibernate操作数据库的核心对象
public class Demo3 {
	
	@Test
	//事务操作
	public void fun1(){
		//1 :创建,调用空参构造+2:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
		Configuration conf = new Configuration().configure();
	
		//2:根据配置信息,创建SessionFactory对象;
		SessionFactory sf = conf.buildSessionFactory();
			
		//3:获得session
		Session session = sf.openSession();
		
		//4:session获得操作事务的Transaction对象
		//获得操作事务的tx对象
		//Transaction tx = session.getTransaction();
		//开启事务并获得操作事务的对象(建议使用)
		Transaction tx2 = session.beginTransaction();
		//--------------------------------------------------
		
		
		
		//--------------------------------------------------
		tx2.commit();//提交事务
		tx2.rollback();//回滚事务
		session.close();//释放资源
		sf.close();//释放资源
	
	}
	
	@Test
	//session的新增功能
	public void fun2(){
		//1 :创建,调用空参构造+2:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
		Configuration conf = new Configuration().configure();
	
		//2:根据配置信息,创建SessionFactory对象;
		SessionFactory sf = conf.buildSessionFactory();
			
		//3:获得session
		Session session = sf.openSession();
		
		//4:session获得操作事务的Transaction对象
		//获得操作事务的tx对象
		//Transaction tx = session.getTransaction();
		//开启事务并获得操作事务的对象(建议使用)
		Transaction tx2 = session.beginTransaction();
		//--------------------------------------------------
		Customer c = new Customer();
		c.setCust_name("宝鸡");
		
		session.save(c);
		
		//--------------------------------------------------
		tx2.commit();//提交事务
		session.close();//释放资源
		sf.close();//释放资源
	
	}
	
	@Test
	//session的查询功能(今天只学习根据id查询)
	//查询id为1的customer对象
	public void fun3(){
		//1 :创建,调用空参构造+2:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
		Configuration conf = new Configuration().configure();
	
		//2:根据配置信息,创建SessionFactory对象;
		SessionFactory sf = conf.buildSessionFactory();
			
		//3:获得session
		Session session = sf.openSession();
		
		//4:session获得操作事务的Transaction对象
		//获得操作事务的tx对象
		//Transaction tx = session.getTransaction();
		//开启事务并获得操作事务的对象(建议使用)
		Transaction tx2 = session.beginTransaction();
		//--------------------------------------------------
		Customer customer = session.get(Customer.class, 1l);//因为customer类中的id字段为Long类型,所以1后面要加一个l
		System.out.println(customer);
		//--------------------------------------------------
		tx2.commit();//提交事务
		session.close();//释放资源
		sf.close();//释放资源
	
	}
	
	@Test
	//session的修改功能
	//查询id为1的customer对象的name属性为黑马程序员
	public void fun4(){
		//1 :创建,调用空参构造+2:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
		Configuration conf = new Configuration().configure();
	
		//2:根据配置信息,创建SessionFactory对象;
		SessionFactory sf = conf.buildSessionFactory();
			
		//3:获得session
		Session session = sf.openSession();
		
		//4:session获得操作事务的Transaction对象
		//获得操作事务的tx对象
		//Transaction tx = session.getTransaction();
		//开启事务并获得操作事务的对象(建议使用)
		Transaction tx2 = session.beginTransaction();
		//--------------------------------------------------
		//1:获得要修改的对象
		Customer customer = session.get(Customer.class, 1l);
		
		//2:修改
		customer.setCust_name("黑马程序员");
		//3:执行update
		session.update(customer);
		
		
		//--------------------------------------------------
		tx2.commit();//提交事务
		session.close();//释放资源
		sf.close();//释放资源
	
	}
	
	@Test
	//session的删除功能
	//删除id为1的customer对象
	public void fun5(){
		//1 :创建,调用空参构造+2:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
		Configuration conf = new Configuration().configure();
	
		//2:根据配置信息,创建SessionFactory对象;
		SessionFactory sf = conf.buildSessionFactory();
			
		//3:获得session
		Session session = sf.openSession();
		
		//4:session获得操作事务的Transaction对象
		//获得操作事务的tx对象
		//Transaction tx = session.getTransaction();
		//开启事务并获得操作事务的对象(建议使用)
		Transaction tx2 = session.beginTransaction();
		//--------------------------------------------------
		//1:获得要修改的对象
		Customer customer = session.get(Customer.class, 1l);
		//2:执行delete
		session.delete(customer);
		
		//--------------------------------------------------
		tx2.commit();//提交事务
		session.close();//释放资源
		sf.close();//释放资源
	
	}
	
}

    五:抽取HibernateUtils:

package yp.itcast.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.jboss.jandex.Main;

public class HibernateUtils {
	
	private static SessionFactory sf = null;
	
	//类的话是由类加载器加载的,类加载器是有一个缓存区,它会把读取到的类缓存起来,
	//		再一次虚拟机运行期间,一个类只会被加载一次,这样的话,静态代码块指挥被运行一次
	static{
		//1 :创建,调用空参构造+2:读取指定配置文件--->空参加载方法,加载src下的hibernate.cfg.xml文件
		Configuration conf = new Configuration().configure();
	
		//2:根据配置信息,创建SessionFactory对象;
		sf = conf.buildSessionFactory();
	}
	
	//获得sesion ---->获得全新session
	public static Session openSession(){

		//3:获得session
		Session session = sf.openSession();
		return session;
	}
	
	//获得session ---->获得与线程绑定的sesion
	public static Session getCurrentSession(){
	
		//3:获得session
		Session session = sf.getCurrentSession();
		return session;
	}
	
	public static void main(String[] args) {
		System.out.println(HibernateUtils.openSession());
	}
}

       

猜你喜欢

转载自blog.csdn.net/qq_40915081/article/details/80868180
今日推荐