hibernate概述
工作dao层orm(对象关系映射)框架
作用:可以自动生成sql,可以自动执行sql,让我们使用面向对象的思想操作数据库.
hibernate学习路线
1.概述,入门案例(配置文件,api)
2.持久化类,主键生成策略,事务,一级缓存,查询的api
3.关联映射(多表)
4.注解开发
学习方法:案例驱动
步骤:
1.创建数据库和表
create database database_62;
use database_62;
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;
2.导入jar包:
hibernate:hibernate解压目录/lib/required/*.jar
驱动:Sql驱动
日志(log4j) 主要作用:记录哪些信息,往哪里输出(控制台还是文件),格式是啥样?
导入log4j的包 必须要导入配置文件:规定保存哪些信息,往哪里输出(控制台还是文件),格式啥样(log4j.properties)
要求:
名称 :log4j.properties
路径 :src目录下
3.创建javabean
public class Customer {
private Long cust_id; //` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
private String cust_name; //` VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)',
private String cust_source; //` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
private String cust_industry; //` VARCHAR(32) DEFAULT NULL COMMENT '客户所属行业',
private String cust_level; //VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
private String cust_phone; // ` VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
private String cust_mobile; //` VARCHAR(16) DEFAULT NULL COMMENT '移动电话',
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_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;
}
4.编写映射文件
格式:xml
名称:自定义 建议:类名.hbm.xml
路径:自定义 建议:和类放在一起
导入约束:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
作用:
配置类和表的映射的,格式入下:
class标签:
name属性:
table属性:
name属性:
column属性:
主键生成策略
property标签:
name属性:
column属性:
下面是我已经编译好的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>
<!--
配置类和表的映射关系
name类的全限定名
table:表名
-->
<class name="cn.xx.domain.Customer" table="cst_customer">
<!--
配置主键和属性的映射
name 配置
table 列名 字段名
-->
<id name="cust_id" column="cust_id" >
<!-- 主键的生成策略 -->
<generator class="native"></generator>
</id>
<!-- 配置属性和其他字段的映射 -->
<property name="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_phone" column="cust_phone"></property>
<property name="cust_mobile" column="cust_mobile"></property>
</class>
</hibernate-mapping>
5.编写核心配置文件
格式:xml或者properties
名称:自定义 建议使用:hibernate.cfg.xml
位置:自定义 建议放在src
导入约束:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
作用:(参考 hibernate解压目录/project/etc/hibernate.properties)
数据库的4个基本信息 property标签
hibernate的属性(是否显示sql,是否格式化sql,方言..) property标签
指定映射文件路径 mapping标签 resource属性
下面是配置好的文件
<!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>
<!-- 数据库连接4个参数 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hibernate01_62</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- hiberante属性 -->
<!-- 是否显示sql -->
<property name="hibernate.show_sql">true</property>
<!-- 是否格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- 方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否由hibernate来生成表ddl语句及如何生成
常见值:
create:由hibernate创建表,每次执行的时候创建一张新表.若之前存在,删除重建;测试用.
create-drop:由hibernate创建表,每次执行的时候创建一张新表.若之前存在,删除重建;
彻底使用完成之后,hibernate删除这表.测试用.
update:由hibernate更新或创建表,若之前没有表,则创建;若现在的表关系发生了该表,还可以自动维护表.常用的
validate:使用表的时候,先校验映射文件和表的映射关系,若对应上了直接使用,若对应不上抛异常
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置C3P0连接池 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 指定映射文件路径 -->
<mapping resource="cn/xx/domain/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6.测试保存
//a.加载核心配置文件
Configuration config = new Configuration().configure()
//b.创建SessionFactory(类似于 连接池)
SessionFactory factory = config.buildSessionFactory();
//c.获取Session(类似于 conn)
Session session = factory.openSession();
//d.开启事务
Transaction tx = session.beginTransaction();
//e. 操作
//f.提交事务
tx.commit();
//g.释放资源
session.close();
配置文件详解
映射文件:
名称:自定义 建议:类名.hbm.xml
路径:自定义 建议:和类放在一起
配置类和表的映射的
class标签:
name属性:类的全限定名
table属性:表名(若类名和表名一样的话,table属性可以省略不写)
id标签 配置oid属性和主键的对应
name:配置OID属性
column:主键列名 字段名(若列名和属性名一样的话,column可以省略)
主键生成策略
property标签 配置其他属性和其他字段的对应
name:配置OID属性
column:字段名(若列名和属性名一样的话,column可以省略)
核心配置文件
名称:自定义 建议使用:hibernate.cfg.xml
位置:自定义 建议放在src
作用:
数据库的4个基本信息 property标签
hibernate的属性(是否显示sql,是否格式化sql,方言..) property标签
update
指定映射文件路径 mapping标签 resource属性
例如:
<mapping resource="cn/xx/domain/Customer.hbm.xml"/>
可以为两种格式:
一种xml(推荐)
一种是properties(不能指定映射文件的路径,使用api加载映射文件)
api详解
Configuration:配置 类
作用:
1.加载核心配置文件
(了解)new Configuration():会自动加载src目录下的名称为 hibernate.properties
★new Configuration().configure():会自动加载src目录下的名称为 hibernate.cfg.xml
(了解)new Configuration().configure(“config/h.c.xml”):会加载src目录下config目录下的 h.c.xml(不用)
2.创建SessionFactory
buildSessionFactory()
3.了解:加载映射文件
addResource(“com/xx/domain/Customer.hbm.xml”);
我们不用第三部=步,因为配置好核心文件的xml是自动加载的
SessionFactory:session工厂
作用:
1.获取Session
openSession()
2.初始化hibernate环境.
3.底层维护了一个连接池.
注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够
抽取一个工具类:
HibernateUtils
提供一个方法 :获取连接
将sessionFactory设为static
代码如下
public class HibernateUtils {
private static SessionFactory factory = null;
static{
factory = new Configuration().configure().buildSessionFactory();
}
public static Session getSession() {
return factory.openSession();
}
}
整合c3p0
1.导入jar包(hibernate解压目录/lib/optional/c3p0/*.jar)
2.在核心配置文件中配置c3p0(配置数据源的提供商)
<!-- 配置C3P0连接池 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
Session:接口 连接对象
作用:
1.开启事务
beginTransaction();
2.和数据库交互
Serializable save(Obejct obj);保存,返回值为id
update(Object obj):修改 先查询再操作
delete(Object obj):删除 先查询再操作
OID查询
T get(Class clazz,Serializable id):根据id返回一个对象
T load(Class clazz,Serializable id):根据id返回一个对象
区别:
get查询的时候会立即发送sql语句,返回的对象本身
load查询的时候不会立即发送sql语句,当使用该对象的非oid属性的时候才会发送.返回的代理对象
(懒(lazy)加载,延迟加载)
Transaction:接口 事务
控制事务
commit();
rollback();
代码
public class CURDDemo {
@Test
public void get() {
//获取连接对象
Session session = HibernateUtils.getSession();
//开事务
Transaction tx = session.beginTransaction();
Customer customer = session.get(Customer.class, 1L);
System.out.println(customer.getCust_name());
tx.commit();
session.close();
}
@Test
public void update(){
//获取连接对象
Session session = HibernateUtils.getSession();
//开事务
Transaction tx = session.beginTransaction();
//先查询 再更新
Customer c = session.get(Customer.class, 1L);
c.setCust_id(1l);
c.setCust_name("张三丰");
session.update(c);
tx.commit();
session.close();
}
@Test
public void delete(){
//获取连接对象
Session session = HibernateUtils.getSession();
//开事务
Transaction tx = session.beginTransaction();
//先查询 再删除
Customer c = session.get(Customer.class, 2L);
session.delete(c);
tx.commit();
session.close();
}
@Test
public void load(){
Session session = HibernateUtils.getSession();
Transaction bx = session.beginTransaction();
Customer c = session.load(Customer.class, 4l);
System.out.println(c.getCust_name());
bx.commit();
session.close();
}
@Test
public void save() {
Session session = HibernateUtils.getSession();
Transaction bx = session.beginTransaction();
Customer c = new Customer();
c.setCust_name("daijiaobu");
Serializable save = session.save(c);
System.out.println(save);
bx.commit();
session.close();
}