Hibernate 简介
Hibernate是一个ORM框架(ORM 对象关系映射),是一个轻量级框架
百度百科:
ORM框架简介
映射指的就是配置文件
Hibernate 环境搭建
具体步骤:
1.导包(先导数据库驱动包,再导日志包,后导Hibernate必须包)
Hibernate5下载地址 :http://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/hibernate-release-5.0.7.Final.zip/download
2.创建表,创建JavaBean
- 表结构
1. 建表语句如下
Create database hibernatedemo01;
Use hibernatedemo01;
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;
- JavaBean
package com.fjut.entity;
import java.io.Serializable;
/**
* 用户实体类
*
*/
public class Customer implements Serializable{
private Long cust_id;
private String cust_name;
private Long cust_user_id;
private Long cust_create_id;
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 Customer() {
}
public Customer(Long cust_id, String cust_name, Long cust_user_id, Long cust_create_id, String cust_source,
String cust_industry, String cust_level, String cust_linkman, String cust_phone, String cust_mobile) {
this.cust_id = cust_id;
this.cust_name = cust_name;
this.cust_user_id = cust_user_id;
this.cust_create_id = cust_create_id;
this.cust_source = cust_source;
this.cust_industry = cust_industry;
this.cust_level = cust_level;
this.cust_linkman = cust_linkman;
this.cust_phone = cust_phone;
this.cust_mobile = 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 Long getCust_user_id() {
return cust_user_id;
}
public void setCust_user_id(Long cust_user_id) {
this.cust_user_id = cust_user_id;
}
public Long getCust_create_id() {
return cust_create_id;
}
public void setCust_create_id(Long cust_create_id) {
this.cust_create_id = cust_create_id;
}
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 + ", cust_user_id=" + cust_user_id
+ ", cust_create_id=" + cust_create_id + ", cust_source=" + cust_source + ", cust_industry="
+ cust_industry + ", cust_level=" + cust_level + ", cust_linkman=" + cust_linkman + ", cust_phone="
+ cust_phone + ", cust_mobile=" + cust_mobile + "]";
}
}
3.配置配置文件
创建类与表结构的映射
- 默认的命名规则为:实体类名.hbm.xml
- 在xml配置文件中引入约束(引入的是hibernate3.0的dtd约束,不要引入4的约束)
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
例子:
Customer.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="com.fjut.entity.Customer" table="cst_customer">
<id name="cust_id" column="cust_id">
<!-- 设置id自增 -->
<generator class="native"></generator>
</id>
<property name="cust_name" column="cust_name" />
<property name="cust_user_id" column="cust_user_id" />
<property name="cust_create_id" column="cust_create_id" />
<property name="cust_source" column="cust_source" />
<property name="cust_industry" column="cust_industry" />
<property name="cust_level" column="cust_level" />
<property name="cust_linkman" column="cust_linkman" />
<property name="cust_phone" column="cust_phone" />
<property name="cust_mobile" column="cust_mobile" />
</class>
</hibernate-mapping>
编写映射的配置文件
1) 在src目录下,创建名称为hibernate.cfg.xml的配置文件
2) 在XML中引入DTD约束
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
3)打开:资料/hibernate-release-5.0.7.Final/project/etc/hibernate.properties,可以查看具体的配置信息
- 必须配置的4大参数
#hibernate.connection.driver_class com.mysql.jdbc.Driver #驱动
#hibernate.connection.url jdbc:mysql:///test #url
#hibernate.connection.username gavin #用户名
#hibernate.connection.password #密码
- 数据库的方言(必须配置的)
#hibernate.dialect org.hibernate.dialect.MySQLDialect
- 可选的配置
#hibernate.show_sql true #显示sql语句
#hibernate.format_sql true #格式化sql语句
#hibernate.hbm2ddl.auto update #自动更新(若没有表会根据映射关系文件自动生成表)
- 引入映射配置文件(一定要注意,要引入映射文件,框架需要加载映射文件,实体类映射文件)
<mapping resource="com/fjut/entity/Customer.hbm.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:///hibernatedemo01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 配置方言 -->
<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>
<!-- 加载映射文件 -->
<mapping resource="com/fjut/entity/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.测试
例子:
@Test
public void testAdd() {
Configuration config = null;
SessionFactory sessionFactory = null;
Session session = null;
Transaction tr = null;
try {
//加载配置文件,默认加载src目录下的配置文件
config = new Configuration().configure();
//获取SessionFactory
sessionFactory = config.buildSessionFactory();
//获取Session对象
session = sessionFactory.openSession();
//开启事务
tr = session.beginTransaction();
//编写保存代码
Customer cus = new Customer();
cus.setCust_name("LGGGX1");
//保存用户
session.save(cus);
//提交事务
tr.commit();
} catch (HibernateException e) {
e.printStackTrace();
//回滚事务
tr.rollback();
}finally {
session.close();
}
}
Hibernate 配置文件简单介绍
1. 映射文件,即 实体类.hbm.xml 的配置文件
<class>标签 -- 用来将类与数据库表建立映射关系
* name -- 类的全路径
* table -- 表名.(类名与表名一致,那么table属性也可以省略)
* catalog -- 数据库的名称,基本上都会省略不写
<id>标签 -- 用来将类中的属性与表中的主键建立映射,id标签就是用来配置主键的。
* name -- 类中属性名
* column -- 表中的字段名.(如果类中的属性名与表中的字段名一致,那么column可以省略.)
* length -- 字段的程度,如果数据库已经创建好了,那么length可以不写。如果没有创建好,生成表结构时,length最好指定。
<property> -- 用来将类中的普通属性与表中的字段建立映射.
* name -- 类中属性名
* column -- 表中的字段名.(如果类中的属性名与表中的字段名一致,那么column可以省略.)
* length -- 数据长度
* type -- 数据类型(一般都不需要编写,如果写需要按着规则来编写)
* Hibernate的数据类型 type="string"
* Java的数据类型 type="java.lang.String"
* 数据库字段的数据类型 <column name="name" sql-type="varchar"/>
Hibernate配置文件之核心配置文件 hibernate.cfg.xml
1. 核心配置文件的两种方式
* 第一种方式是属性文件的形式,即properties的配置文件
* hibernate.properties
* hibernate.connection.driver_class=com.mysql.jdbc.Driver
* 缺点
* 不能加载映射的配置文件,需要手动编写代码去加载
* 第二种方式是XML文件的形式,开发基本都会选择这种方式
* hibernate.cfg.xml
* <property name="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property>
* 优点
* 格式比较清晰
* 编写有提示
* 可以在该配置文件中加载映射的配置文件(最主要的)
2. 关于hibernate.cfg.xml的配置文件方式
* 必须有的配置
* 数据库连接信息:
hibernate.connection.driver_class -- 连接数据库驱动程序
hibernate.connection.url -- 连接数据库URL
hibernate.connection.username -- 数据库用户名
hibernate.connection.password -- 数据库密码
* 方言:
hibernate.dialect -- 操作数据库方言
* 可选的配置
* hibernate.show_sql -- 显示SQL
* hibernate.format_sql -- 格式化SQL
* hibernate.hbm2ddl.auto -- 通过映射转成DDL语句
* create -- 每次都会创建一个新的表.---测试的时候
* create-drop -- 每次都会创建一个新的表,当执行结束之后,将创建的这个表删除.---测试的时候
* update -- 如果有表,使用原来的表.没有表,创建一个新的表.同时更新表结构.
* validate -- 如果有表,使用原来的表.同时校验映射文件与表中字段是否一致如果不一致就会报错.
* 加载映射
* 如果XML方式:<mapping resource="com/fjut/entity/Customer.hbm.xml"/>
Hibernate 常用接口及类讲解
Configuration类
- Configuration对象用于配置并且启动Hibernate。
- Hibernate应用通过该对象来获得对象-关系映射文件中的元数据,以及动态配置Hibernate的属性,然后创建SessionFactory对象。
- 简单一句话:加载Hibernate的配置文件,可以获取SessionFactory对象。
SessionFactory
- 是工厂类,是生成Session对象的工厂类
SessionFactory类的特点
- 由Configuration通过加载配置文件创建该对象。
- SessionFactory对象中保存了当前的数据库配置信息和所有映射关系以及预定义的SQL语句。同时,SessionFactory还负责维护Hibernate的二级缓存。
- 一个SessionFactory实例对应一个数据库,应用从该对象中获得Session实例。
- SessionFactory是线程安全的,意味着它的一个实例可以被应用的多个线程共享。
- SessionFactory是重量级的,意味着不能随意创建或销毁它的实例。如果只访问一个数据库,只需要创建一个SessionFactory实例,且在应用初始化的时候完成。
- SessionFactory需要一个较大的缓存,用来存放预定义的SQL语句及实体的映射信息。另外可以配置一个缓存插件,这个插件被称之为Hibernate的二级缓存,被多线程所共享
Session
1概述
- Session是在Hibernate中使用最频繁的接口。也被称之为持久化管理器。它提供了和持久化有关的操作,比如添加、修改、删除、加载和查询实体对象
- Session 是应用程序与数据库之间交互操作的一个单线程对象,是 Hibernate 运作的中心
- Session是线程不安全的
- 所有持久化对象必须在 session 的管理下才可以进行持久化操作
- Session 对象有一个一级缓存,显式执行 flush 之前,所有的持久化操作的数据都缓存在 session 对象处
- 持久化类与 Session 关联起来后就具有了持久化的能力
特点
- 不是线程安全的。应避免多个线程使用同一个Session实例
- Session是轻量级的,它的创建和销毁不会消耗太多的资源。应为每次客户请求分配独立的Session实例
- Session有一个缓存,被称之为Hibernate的一级缓存。每个Session实例都有自己的缓存
常用的方法
- save(obj)
- delete(obj)
- get(Class,id)
- update(obj)
- saveOrUpdate(obj) – 保存或者修改(如果没有数据,保存数据。如果有,修改数据)
- createQuery() – HQL语句的查询的方式
Transaction接口
- Transaction是事务的接口
常用的方法
- beginTransaction() –开启事务
- commit() – 提交事务
- rollback() – 回滚事务
特点
- Hibernate框架默认情况下事务不自动提交.需要手动提交事务
- 如果没有开启事务,那么每个Session的操作,都相当于一个独立的事务
Hibernate 基本操作
增加 save(obj):
@Test
public void testAdd() {
Session session = null;
Transaction tr = null;
try {
//获取Session对象
session = SessionUtils.getSession();
//开启事务
tr = session.beginTransaction();
//编写保存代码
Customer cus = new Customer();
cus.setCust_name("LGGGX");
//保存用户
Serializable saveId = session.save(cus);
//打印id
System.out.println(saveId);
//提交事务
tr.commit();
} catch (HibernateException e) {
e.printStackTrace();
//回滚事务
tr.rollback();
}finally {
session.close();
}
}
查询 get(Class,id)
@Test
public void testGet() {
Session session = SessionUtils.getSession();
// 查询
Customer customer = session.get(Customer.class, 97L);
System.out.println(customer);
session.close();
}
删除 delete(obj)
@Test
public void testDel() {
Session session = null;
Transaction tr = null;
try {
session = SessionUtils.getSession();
//开启事务
tr = session.beginTransaction();
//先查再删
Customer customer = session.get(Customer.class, 98L);
System.out.println(customer);
//删除
session.delete(customer);
//提交事务
tr.commit();
} catch (Exception e) {
e.printStackTrace();
tr.rollback();
}finally {
session.close();
}
}
修改 update(obj)
@Test
public void testUpdate() {
Session session = null;
Transaction tr = null;
try {
// 获取Session对象
session = SessionUtils.getSession();
// 开启事务
tr = session.beginTransaction();
// 查询
Customer customer = session.get(Customer.class, 97L);
customer.setCust_name("HHH-HHH");
// 更新用户
session.update(customer);
// 提交事务
tr.commit();
} catch (HibernateException e) {
e.printStackTrace();
// 回滚事务
tr.rollback();
} finally {
session.close();
}
}
HQL查询 createQuery(HQL)
@Test
public void testQuery() {
Session session = SessionUtils.getSession();
// 查询
String HQL = "from Customer";
Query query = session.createQuery(HQL);
//获取List集合
List<Customer> list = query.list();
for (Customer customer : list) {
System.out.println(customer);
}
session.close();
}
Hibernate 第一天案例
完成简易增删改查操作
文件地址:链接:https://pan.baidu.com/s/11uqdRDKGIfYo3yhGekwCrw 密码:mz6b