Hibernate第一天(Hibernate的环境搭建、Hibernate的API、Hibernate的CRUD)
1.1以前学习过Hibernate,不过学习的不太扎实,做的项目也不太多,好久时间没用,都快忘得差不多了,今天重新学习一下,一步一个脚印的敲每个代码,争取把Hibernate彻底学明白。
第一天:Hibernate的入门(Hibernate的环境搭建、Hibernate的API、Hibernate的CRUD)
第二天:Hibernate的一级缓存、其他的API
第三天:Hibernate的一对多配置、Hibernate的多对多的配置
第四天:Hibernate的查询方式、抓取策略
框架:指的是软件的半成品,已经完成了部分功能。
Hibernate:Hibernate是一个持久层的ORM框架。
ORM:Object RelationalMapping(对象关系映射)。指的是将一个Java中的对象与关系型数据库中的表建立一种映射关系,从而操作对象就可以操作数据库中的表。
Hibernate3.x Hibernate4.x Hibernate5.x(我这里使用5.0.7)
下载地址:https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/
1.documentation :Hibernate开发的文档
2.lib :Hibernate开发包
2.1required :Hibernate开发的必须的依赖包
2.2optional :Hibernate开发的可选的jar包
3.project :Hibernate提供的项目
1.数据库驱动包,2.Hibernate开发的必须的jar包,3.Hibernate引入日志记录包,4.C3p0连接池
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=1DEFAULT CHARSET=utf8;
映射需要通过XML的配置文件来完成,这个配置文件可以任意命名。尽量统一命名规范(类名.hbm.xml)
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属性:类的全路径
*table属性:表名(如果表名和类名一致可忽略)
*catalog属性:数据库名称,可忽略
-->
<class name="top.yangxianyang.demo1.Customer" table="cst_customer">
<!--建立类中的属性与表中的主键对应 -->
<!--
id标签:建立类中的属性与表中的主键对应
*name属性:类中的属性名
*column属性:表中字段名(如果类中属性名和表中字段名一致,可省略)
*catalog属性:数据库名称,可忽略
*length属性:字段长度
*type属性:类型。写Java数据类型,Hibernate数据类型(默认),SQL类型
-->
<id name="cust_id" column="cust_id" >
<!--主键生成策略 -->
<generator class="native"/>
</id>
<!--建立类中的普通的属性和表的字段的对应 -->
<!--
property标签:建立类中的普通的属性和表的字段的对应
*name属性:类中的属性名
*column属性:表中字段名(如果类中属性名和表中字段名一致,可省略)
*length属性:字段长度
*type属性:类型。写Java数据类型,Hibernate数据类型(默认),SQL类型
-->
<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>
Hibernate的核心配置文件的名称: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:///sshstudy</property>
<property name="hibernate.connection.username">yxy</property>
<property name="hibernate.connection.password">123456</property>
<!-- 配置Hibernate的方言:作用,根据配置的方言生成相应的SQL语句 -->
<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>
<!-- 加载映射 -->
<mapping resource="top/yangxianyang/demo1/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
1.4.1.8 编写测试代码(*****)
package top.yangxianyang.demo1;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* Hibernate的入门案例
* @author yxy
*
*/
publicclass Test1 {
publicstaticvoid main(String[] args) {
demo1();
}
// 保存客户
publicstaticvoid demo1() {
// 1.加载Hibernate的核心配置文件
Configuration configuration = newConfiguration().configure();
// 2.创建一个SessionFactory对象:类似于JDBC中连接池
SessionFactory sessionFactory =configuration.buildSessionFactory();
// 3.通过SessionFactory获取到Session对象:类似于JDBC中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();
sessionFactory.close();
}
}
l 【class标签的配置】
n 标签用来建立类与表的映射关系
n 属性:
u name :类的全路径
u table :表名(类名与表名一致,table可以省略)
u catalog :数据库名
l 【id标签的配置】
n 标签用来建立类中的属性与表中的主键的对应关系
n 属性:
u name :类中的属性名
u column :表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
u length :长度
u type :类型
l 【property标签的配置】
n 标签用来建立类中的普通属性与表的字段的对应关系
n 属性:
u name :类中的属性名
u column :表中的字段名
u length :长度
u type :类型
u not-null :设置非空
u unique :设置唯一
第一种方式:属性文件的方式
hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver
…
hibernate.show_sql=true
属性文件的方式不能引入映射文件(手动编写代码加载映射文件)
第二种方式:XML文件的方式
hibernate.cfg.xml(推荐)
l 必须的配置
n 连接数据库的基本的参数
u 驱动类
u url路径
u 用户名
u 密码
n 方言
l 可选的配置
n 显示SQL :hibernate.show_sql
n 格式化SQL :hibernate.format_sql
n 自动建表 :hibernate.hbm2ddl.auto
u none :不使用hibernate的自动建表
u create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
u create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
u update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
u validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
l 映射文件的引入
n 引入映射文件的位置
l
l
l
l 作用:
n 加载核心配置文件
u hibernate.properties
Configuration cfg= new Configuration();
u hibernate.cfg.xml
Configuration cfg = newConfiguration().configure();
n 加载映射文件
// 手动加载映射
configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml";
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存。是线程安全的对象。一个项目创建一个对象即可。
l hibernate配置C3P0连接池:
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-configurationPUBLIC
"-//Hibernate/Hibernate ConfigurationDTD 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:///sshstudy</property>
<property name="hibernate.connection.username">yxy</property>
<property name="hibernate.connection.password">123456</property>
<!-- 配置Hibernate的方言:作用,根据配置的方言生成相应的SQL语句 -->
<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>
<!-- 配置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="top/yangxianyang/demo1/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
l 封装工具类
package com.itheima.hibernate.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate的工具类
* @author yxy
*
*/
publicclass HibernateUtils {
publicstaticfinal Configuration cfg;
publicstaticfinal SessionFactory sf;
static{
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
publicstatic Session openSession(){
returnsf.openSession();
}
}
Session代表的是Hibernate与数据库的链接对象。不是线程安全的。与数据库交互桥梁。
l Session中的API
n 保存方法:
u Serializablesave(Object obj);
n 查询方法:
u Tget(Class c,Serializable id);
u Tload(Class c,Serializable id);
u get方法和load方法的区别?
get方法
* *采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
* * 查询后返回是真实对象本身。
* * 查询一个找不到的对象的时候,返回null
load方法
* * 采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
* * 查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
* * 查询一个找不到的对象的时候,返回ObjectNotFoundException
n 修改方法
u voidupdate(Object obj);
n 删除方法
u void delete(Object obj);s
n 保存或更新
u voidsaveOrUpdate(Object obj)
n 查询所有
u List createSQLQuery(Stringsql)
测试代码:
package top.yangxianyang.demo1;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.itheima.hibernate.utils.HibernateUtils;
/**
* Hibernate的工具类的测试
* @author yxy
*
*/
publicclass TestUtils {
@Test
// 保存客户
publicvoid demo1(){
Session session = HibernateUtils.openSession();
Transaction tx =session.beginTransaction();
Customer customer = new Customer();
customer.setCust_name("王小西");
Serializable id =session.save(customer);
System.out.println(id);
tx.commit();
session.close();
}
@Test
// 查询:
// ***** get方法和load方法的区别
publicvoid demo2(){
Session session = HibernateUtils.openSession();
Transaction tx =session.beginTransaction();
/**
*get方法
* * 采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
* * 查询后返回是真实对象本身。
* * 查询一个找不到的对象的时候,返回null
*
*load方法
* * 采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
* * 查询后返回的是代理对象。javassist-3.18.1-GA.jar 利用javassist技术产生的代理。
* * 查询一个找不到的对象的时候,返回ObjectNotFoundException
*/
// 使用get方法查询
/*Customer customer = session.get(Customer.class, 1l); // 发送SQL语句
System.out.println(customer);*/
// 使用load方法查询
Customer customer =session.load(Customer.class, 1l);
System.out.println(customer);
tx.commit();
session.close();
}
@Test
// 修改操作
publicvoid demo3(){
Session session = HibernateUtils.openSession();
Transaction tx =session.beginTransaction();
// 直接创建对象,进行修改
/*Customer customer = new Customer();
customer.setCust_id(1l);
customer.setCust_name("王聪");
session.update(customer);*/
// 先查询,再修改(推荐)
Customer customer =session.get(Customer.class, 1l);
customer.setCust_name("王小贱");
session.update(customer);
tx.commit();
session.close();
}
@Test
// 删除操作
publicvoid demo4(){
Session session = HibernateUtils.openSession();
Transaction tx =session.beginTransaction();
// 直接创建对象,删除
/* Customer customer = new Customer();
customer.setCust_id(1l);
session.delete(customer);*/
// 先查询再删除(推荐)--级联删除
Customer customer =session.get(Customer.class, 2l);
session.delete(customer);
tx.commit();
session.close();
}
@Test
// 保存或更新
publicvoid demo5(){
Session session = HibernateUtils.openSession();
Transaction tx =session.beginTransaction();
/*Customer customer = newCustomer();
customer.setCust_name("王凤");
session.saveOrUpdate(customer);*/
Customer customer = new Customer();
customer.setCust_id(3l);
customer.setCust_name("李如花");
session.saveOrUpdate(customer);
tx.commit();
session.close();
}
@Test
// 查询所有
publicvoid demo6(){
Session session = HibernateUtils.openSession();
Transaction tx =session.beginTransaction();
// 接收HQL:Hibernate Query Language 面向对象的查询语言
/*Query query = session.createQuery("from Customer");
List<Customer> list =query.list();
for (Customer customer : list) {
System.out.println(customer);
}*/
// 接收SQL:
SQLQuery query = session.createSQLQuery("select * from cst_customer");
List<Object[]> list = query.list();
for (Object[]objects : list) {
System.out.println(Arrays.toString(objects));
}
tx.commit();
session.close();
}
}
Hibernate中管理事务的对象。
commit();
rollback();
源码地址:
链接:https://pan.baidu.com/s/1cYbNGrbGu3NPOiIPTpzqOw密码:y8kj
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有