Hibernate_01

本文介绍了使用Hibernate完成CRM客户管理系统的CRUD操作。首先解释了CRM的含义和功能,接着详细阐述了Hibernate作为Java持久层框架的作用和学习价值。在Hibernate的入门部分,包括了下载Hibernate、创建数据库和表、引入JAR包、创建实体类和映射文件、配置文件的设置等步骤,最后讲解了Configuration和SessionFactory这两个关键API的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例一:

使用Hibernate完成CRM客户管理的CRUD的操作

1.1 需求描述

CRM系统中客户信息管理模块功能包括:
新增客户信息
客户信息查询
修改客户信息
删除客户信息

1.2 CRM的概述

1.2.1 什么是 CRM

CRM (Customer Relationship Management)客户关系管理,是利用相应的信息技术以及互联网技术来
协调企业与顾客间在销售、营销和服务上的交互,向客户提供创新式的个性化的客户交互和 服务的过
程。其最终目标是将面向客户的各项信息和活动集成起来,组建一个以客户为中心的企业, 实现对面向客
户的活动的全面管理。


1.2.2 CRM的功能模块

CRM系统实现了对企业销售、营销、服务等各阶段的客户信息、客户活动进行统一管理。
CRM系统功能涵盖企业销售、营销、用户服务等各各业务流程,业务流程中与客户相关活动都会在
CRM系统统一管理,下边列出一些基本的功能模块,包括:客户信息管理、联系人管理、商机管理、统
计分析等。

客户信息管理
对客户信息统一维护,客户是指存量客户或拟营销的客户,通过员工录入形成公司的“客户库” 是公司最
重要的数据资源。
联系人管理
对客户的联系人信息统一管理,联系人是指客户企业的联系人,即企业的业务人员和客户的哪 些人在打
交道。
客户拜访管理:
业务员(用户)要开发客户需要去拜访客户,客户拜访信息记录了业务员与客户沟通交流方面 的不足、
采取的策略不当、有待改进的地方或值得分享的沟通技巧等方面的信息。
综合查询
客户相关信息查询,包括:客户信息查询、联系人信息查询、商机信息查询等。
统计分析
按分类统计客户信息,包括:客户信息来源统计、按行业统计客户、客户发展数量统计等。
系统管理
系统管理属于erm系统基础功能模块,包括:数据字典、账户管理、角色管理、权限管理、操 作日志管
理等。

1.2.3 JavaEE开发的三层结构

1.3 Hibernate概述

1.3.1 什么是 Hibernate

Hibernate框架是当今主流的Java持久层框架之一,由于它具有简单易学、灵活性强、扩展性强 等特
点,能够大大地简化程序的代码量,提高工作效率,因此受到广大开发人员的喜爱。
Hibernate是一个开放源代码的ORM (Object Relational Mapping,对象关系映射)框架,它对 JDBC进
行了轻量级的对象封装,使得Java开发人员可以使用面向对象的编程思想来操作数据库。

Hibernate就是一个持久层的0RM的框架.
0RM :Object Relational Mapping.对象关系映射.

1.3.2 为什么要学习 Hibernate
 

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

与其它操作数据库的技术相比,Hibernate具有以下几点优势∶


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

1.3.3 Hibernate的入门∶

1.3.3.1下载Hibernate5

https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/

网盘:链接:https://pan.baidu.com/s/1H4-9pdFDVGX1NOSy_QxW6w 提取码:ztcr

Hibernate5.0.7版本下载后,解压完的目录结构如图所示。

从图可以看出,hibemate5.0.7的解压s目录中包含一系列的子目录,这些子目录分别用于存放不同 功能
的文件,接下来针对这些子目录进行简单介绍,具体如下:
 

documentation文件夹:存放Hibernate的相关文档,包括参考文档的API文档。
lib文件夹:存放Hibernate编译和运行所依赖的JAR包。其中required子目录下包含了运 行
Hibernate5项目必须的JAR包。
project文件夹:存放Hibernate各种相关的源代码。
在hb/required子目录中,包含的JAR包

1.3.3.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_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;

cust_id : 那个类型都可以的 

 

1.3.3.3 引入 Hibernate 开发的 jar 包

数据库驱动包

Hibernate/lib/required/*.jar

日志记录的包:

1.3.3.4 创建实体(持久化类)

持久化类是应用程序中的业务实体类,这里的持久化是指类的对象能够被持久化保存到数据库中。
Hibernate使用普通Java对象(Plain Old Java Object),即POJO的编程模式来进行持久化。POJO类 中包含
的是与数据库表相对应的各个属性,这些属性通过getter和setter方法来访问,对外部隐藏了 内部的实
现细节。下面就来编写Customer持久化类。
在项目src目录下,创建包,并在包中创建实体类Customer (对应数据库表cst_customer), Customer类
包含与cst_customer数据表字段对应的属性,以及相应的getXxx ()和setXxx ()方法。

 

package com.dd.pojo;

public class Customer {
	private Integer 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();
	}
	public Customer(Integer 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;
	}
	
	public Customer(String cust_name, String cust_source, String cust_industry, String cust_level, String cust_phone,
			String cust_mobile) {
		super();
		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;
	}
	public Integer getCust_id() {
		return cust_id;
	}
	public void setCust_id(Integer 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 + "]";
	}
	
	
	

}

1.3.3.5 创建映射文件

实体类Customer目前还不具备持久化操作的能力,而Hibernate需要知道实体类Customer映射到数 据
库Hibernate中的哪个表,以及类中的哪个属性对应数据库表中的哪个字段,这些都需要在映射文 件中
配置。
在实体类Customer所在的包中,创建一个名称为Customer.hbm.xml的映射文件,在该文件中定义了
实体类Customer的属性是如何映射到cst_customer表的列上的。

<?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.dd.pojo.Customer" table="cst_customer">
	<!--建立类中的属性与表中的主键的映射关系 -->
		<id name="cust_id" column="cust_id">
			<!--主键的生成策略 -->
			<generator class="native"></generator>
		</id>
		<!-- 建立类中的普通属性与表中的字段的映射 -->
		<property name="cust_name" column="cust_name"/>
		<property name="cust_source" column="cust_source" />
		<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>

1.3.3.6 创建 Hibernate 的核心配置文件

Hibernate的映射文件反映了持久化类和数据库表的映射信息,而Hibernate的配置文件则主要用来配 置
数据库连接以及Hibernate运行时所需要的各个属性的值。在项目的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>
		<!-- 必要的配置信息,连接数据库的基本参数 -->
		
		<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>	
		
		
		<!-- 配置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>
		
		
		
		
		<!-- Hibernate 的方言:根据配置的方言生成对应的 SQL 语句 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
			
		<!-- Hibernate 显示 SQL 语句: -->
		<property name="hibernate.show_sql">true</property>	
		<!-- Hibernate 格式化 SQL 语句: -->
		<property name="hibernate.format_sql">true</property>	
		
		<!-- 加载映射文件 -->
		<mapping resource="com/dd/pojo/Customer.hbm.xml"/>
		
		</session-factory>
	
	</hibernate-configuration>

1.3.3.7 编写测试代码
 

package com.dd.test;

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

import com.dd.pojo.Customer;

public class HibernateTest {
	@Test
	public void saveData() {
		//1 .加载配置文件
		Configuration cfg = new Configuration().configure();
		//2. 创建一个 SessionFactory
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		//3. 创建 Session 对象 Session 对象类似于 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();
		
	}

}

首先创建Configuration类的实例,并通过它来读取并解析配置文件hibernate.cfg.xml。然后创建
SessionFactory读取解析映射文件信息,并将Configuration对象中的所有配置信息拷贝到
SessionFactory内存中。接下来,打开Session,让SessionFactory提供连接,并开启一个事务,之后 创
建对象,向对象中添加数据,通过session.saveQ方法完成向数据库中保存数据的操作。最后提交 事
务,并关闭资源。

1.3.4 Hibernate的常见配置

在案例中,已经接触过Hibernate的映射文件和配置文件。接下来,将对这些文件进行详细的讲解。

在xml文件中,没有提示需要配一下配置:

1.3.4.1 XML 提示的配置
 

1.3.4.2 映射文件的配置

该文件用于向Hibernate提供持久化类到关系型数据库的映射,每个映射文件的的结构基本都是相同
的,其普遍的代码形式如下所示。

<?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.dd.pojo.Customer" table="cst_customer">
	<!--建立类中的属性与表中的主键的映射关系 -->
		<id name="cust_id" column="cust_id">
			<!--主键的生成策略 -->
			<generator class="native"></generator>
		</id>
		<!-- 建立类中的普通属性与表中的字段的映射 -->
		<property name="cust_name" column="cust_name"/>
		<property name="cust_source" column="cust_source" />
		<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>

映射文件通常是一个XML文件即可,但一般命名为 类名.hbm.xml

【class标签】

【class标签的配置】
      标签用来建立类与表的映射关系
         属性:
            name :类的全路径
            table :表名(类名与表名一致,table可以省略)
            catalog :数据库名

【id标签】

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

【property标签】

【property标签的配置】
标签用来建立类中的普通属性与表的字段的对应关系
属性:
     name :类中的属性名
     column :表中的字段名
     length :长度

     type :类型
     not-null :设置非空
     unique :设置唯一

1.3.4.3 核心配置文件的配置

必须的配置
     连接数据库的基本的参数
     驱动类
     用户名
     密码
      方言

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

映射文件的引入

引入映射文件的位置

1.3.5 Hibernate 的相关 API

1.3.5.1 Configuration:配置对象

Configuration主要用于Hibernate框架加载映射文件

【加载核心配置文件】
       在使用Hibernate时,首先要创建Configuration实例,Configuration实例主要用于启动、加载、
管理hibernate的配置文件信息。在启动Hibernate的过程中,Configuration实例首先确定Hibernate 配
置文件的位置,然后读取相关配置,最后创建一个唯一的SessionFactory实例。Configuration对象 只存
在于系统的初始化阶段,它将SessionFactory创建完成后,就完成了自己的使命。


     Hibernate 通常使用 Configuration config = new Configuration().configure();的方式创建实例,此
种 方式默认会去src下读取hibernate.cfg.xml配置文件。如果不想使用默认的hibernate.cig.xml配置文
件,而是使用指定目录下(或自定义)的配置文件,则需要向configureQ方法中传递一个文件路径 的参
数,其代码写法如下:

Configuration config = new Configuration ().configure ( "xml 文件位置");

此种写法hibernate会去指定位置查找配置文件,例如,想要使用src下config包中的
hibernate.cfg.xml文件,只需将文件位置加入configure()中即可,其代码如下所示:

Configuration config = new
Configuration().configure("/config/hibernate.cfg.xml");

【加载映射文件】
      Hibernate除了可以使用Configuration对象加载核心配置文件以夕卜,还可以利用该对象加载映射
文件。因为如何使用properties文件作为Hibernate的核心配置文件,其他的属性可以使用key=value 的
格式来设置,但是映射没有办法加载。这时这个对象就有了用武之地。可以在手动编写代码的时 候去加
载映射文件。

Configuration configuration = new Configuration ().configure("xml文件位置");
configuration.addResource("com/admiral/domain/Customer.hbm.xml");

1.3.5.2 SessionFactory: Session 工厂对象

SessionFactory接口负责Hibernate的初始化和建立Session对象。它在Hibernate中起到一个缓 冲
区作用,Hibernate可以将自动生成的SQL语句、映射数据以及某些可重复利用的的数据放在这个 缓冲
区中。同时它还保存了对数据库配置的所有映射关系,维护了当前的二级缓存。

SessionFactory实例是通过Configuration对象获取的,其获取方法如下所示。

SessionFactory sessionFactory = config.buildsessionFactory();

SessionFactory具有以下特点:

它是线程安全的,它的同一个实例能够供多个线程共享。
它是重量级的,不能随意的创建和销毁它的实例。

 

       由于SessionFactory的这些特点,一般情况下,一个项目中只需要一个SessionFactory,只有当 应用
中存在多个数据源时,才为每个数据源建立一个SessionFactory实例。因此,在实际项目使用中, 通常
会抽取出一个HibernateUtils的工具类,用来提供Session对象。

package com.dd.utils;

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

public class HibernateUtils {
	public static final Configuration CONFIGURATION;
	public static final SessionFactory SESSION_FACTORY;
	
	static {
		
		CONFIGURATION=new Configuration().configure();
		SESSION_FACTORY=CONFIGURATION.buildSessionFactory();
		
	}
	/**
	 * 提供获得 Session 的方法
	 * @return
	 */
	public Session openSession() {
		return SESSION_FACTORY.openSession();
	}

}

SessionFactory内部还维护了一个连接池,如果我们需要使用第三方的连接池如C3P0,那么需要我
们自己手动进行配置 配置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>

如果:

如果出现以上问题可能是:没有导包或配置文件

上面四个都不能少;

项目:链接:https://pan.baidu.com/s/106hnqQOCUsQWUD4AxFW5Jw 提取码:ysr0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值