Hibernate_day01

第1章 Hibernate_day01

1.1 Hibernate的学习路线

n Hibernate的入门和流程

n Hibernate的一级缓存,对象的状态

n Hibernate的关联关系映射

n Hibernate的查询方式和检索策略

1.2 CRM的管理的CRUD的操作

1.2.1 Hibernate的概述

1.2.1.1 什么是Hibernate

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的 orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命 意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。

Hibernate是一个持久层的ORM框架。

1.2.1.2 什么是ORM

ORM:Object Relational Mapping。对象关系映射。开发语言用的是Java,面向对象的(Object)。使用的数据库是关系型数据库(Relational)。就是将对象与数据库中的表建立一种映射关系,操作对象就可以操作这个表。

1.2.2 Hibernate的入门

1.2.2.1 步骤一:下载Hibernate开发包

下载地址:

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

1.2.2.2 步骤二:Hibernate的目录结构

 

1.2.2.3 步骤三:创建WEB工厂,引入jar包

创建web工程。

D:\hibernate-release-5.0.7.Final\lib\required\*.jar

数据库驱动包

日志记录的包

 

1.2.2.4 步骤四:创建数据库和表

 

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;

1.2.2.5 步骤五:创建实体类

public class Customer {

private Long 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 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;

}

}

1.2.2.6 步骤六:创建映射

映射文件通常有一个命名规则:类名.hbm.xml

引入约束:

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

 

<?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>

<!-- ORM:Object Relational Mapping,将实体类O和数据库的表R 建立映射关系 -->

<class name="com.itheima.hibernate.domain.Customer" table="cst_customer">

<!-- 类中的属性与表中的主键对应 -->

<id name="cust_id" column="cust_id">

<generator class="native"/>

</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.2.2.7 步骤七:创建Hibernate的核心配置文件

<?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_day01</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password">123</property>

<!-- 数据库的方言:根据底层的数据库生成不同的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>

<!-- 配置hbm2ddl -->

<property name="hibernate.hbm2ddl.auto">update</property>

<!-- 加载映射文件 -->

<mapping resource="com/itheima/hibernate/domain/Customer.hbm.xml"/>

</session-factory>

</hibernate-configuration>

1.2.2.8 步骤八:编写测试方法

public class HibernateDemo1 {

 

@Test

/**

 * 保存操作

 */

public void demo1(){

// 加载Hibernate的核心配置文件.

Configuration configuration = new Configuration().configure();

// 创建一个SessionFactory的对象.

SessionFactory sessionFactory = configuration.buildSessionFactory();

// 创建Session(相当于JDBC中的Connection)

Session session = sessionFactory.openSession();

// 开启事务:

Transaction transaction = session.beginTransaction();

// 完成操作:

Customer customer = new Customer();

customer.setCust_name("柳岩");

session.save(customer);

// 提交事务

transaction.commit();

// 释放资源

session.close();

}

}

1.2.3 Hibernate的常用的配置

1.2.3.1 Hibernate的配置文件的提示

 

1.2.3.2 Hibernate的映射文件的配置

class的配置

 

Id和property的配置

 

主键生成策略:

increment:

 * 自动增加的方式生成唯一标识,每次增加1 ,适用于: long int  short 类型

 *

 * 原理:每次保存数据的时候都是先查询数据库中主键的最大值,再加1,生成下个一插入的主键

 *

 * 缺点:线程不安全

 *

   identify:

 * 条件:数据库支持自动增长数据类型

 * mysql, db2, sqlserver 

 *

    sequence:

 * 条件:数据库支持序列

 * oracle, db2

   native:

 * 智能选择,看底层数据库是什么,自动选择identify 和 sequence

 *

   uuid: 

 * 条件主键是字符串类型

 *  

   assligned:

 *   hibernate 不管唯一标识生成策略,但是每次保存数据的时候必须手动添加主键

 *

 

1.2.3.3 Hibernate的核心配置文件的配置

Hibernate的核心配置文件有两种方式:

【属性文件的方式】

需要在src下创建一个hibernate.properties文件

配置:key=value

hibernate.connection.driver_class=com.mysql.jdbc.Drvier

 

属性文件的方式:结构不是很清晰而且这种方式不能加载映射文件。需要手动编写代码才能加载映射文件。

【XML配置文件的方式】

数据库的基本参数:

 

Hibernate的属性

 

hibernate.hbm2ddl.auto有几个取值

* none:不使用映射转成DDL。

* create:如果原来有表将原有的表删除。每次都会新创建一个表。测试的时候使用。

* create-drop:如果原来有表将原有的表删除。每次都会新创建一个表。执行完操作以后会将表删除掉。测试的时候使用。

* update果数据库中有表使用原来的表。如果没有表会创建一个表。而且可以更新原有表结构。:如

* validate:不会创建表。校验映射和表结构是否正确

映射文件的加载

 

1.2.4 Hibernate的常用的API

1.2.4.1 Configuration:配置对象

Configuration是一个配置对象,作用主要有两个,一个用来加载核心配置文件。另一个用来加载映射文件。

【加载核心配置文件】

加载hibernate.properties

Configuration cfg = new Configuration();//默认加载properties文件

 

加载hibernate.cfg.xml

Configuration cfg = new Configuration().configure();

【加载映射文件】

// 手动加载映射文件

// configuration.addResource("com/itheima/hibernate/domain/Customer.hbm.xml");

// configuration.addClass(Customer.class);

1.2.4.2 SessionFactory:Session工厂

SessionFactory负责管理Session,管理连接池,管理Hibernate二级缓存。采用了工厂模式,不是一个轻量级的对象。通常情况下一个项目只对应一个SessionFactory就够了。是线程安全的对象。

【抽取Hibernate的工具类】

public class HibernateUtils {

 

private static final Configuration configuration;

private static final SessionFactory sessionFactory;

static{

configuration = new Configuration().configure();

sessionFactory = configuration.buildSessionFactory();

}

public static Session openSession(){

return sessionFactory.openSession();

}

}

【配置C3P0连接池】

引入c3p0连接池的jar包:

 

配置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>

1.2.4.3 Session:相当于Connection

Session是Hibernate程序与数据库之间的桥梁。完成CRUD的操作。Session是一个单线程的对象,内部维护了Hibernate的一级缓存(session级别的缓存)。

【Session保存某个对象】

@Test

/**

 * 保存客户

 */

public void demo1(){

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

Customer customer = new Customer();

customer.setCust_name("梁");

session.save(customer);// 保存对象

tx.commit();

session.close();

}

【Session查询某个对象】

@Test

/**

 * 查询某个对象

 * 面试:get方法和load方法的区别?

 * * get方法采用的是立即加载,执行到该行代码的时候,马上发送SQL语句进行查询。查询之后返回的是真实对象本身。

 * 查询一个找不到的对象返回null.

 *  * load方法采用的是延迟加载(lazy),执行到行的代码的时候,不会马上发送SQL语句,

 *  只有真正使用这个对象的时候(使用这个对象的普通属性的时候)才会发送SQL语句。

 *      load方法返回的是代理对象。(产生的是Customer的子类对象)

 *      查询一个找不到的对象抛出异常:ObjectNotFoundException

 */

public void demo2(){

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

// 调用session.get()方法查询某个对象。

//Customer customer = session.get(Customer.class, 100l);// 马上发送SQL语句.

// 调用session.load()方法查询某个对象。

Customer customer = session.load(Customer.class, 300l);// 不会马上发送SQL语句.

System.out.println(customer);

tx.commit();

session.close();

}

【Session中修改某个对象的方法】

@Test

/**

 * 修改某个对象

 */

public void demo3(){

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

// 1.直接创建对象进行修改.(没有设置的属性会被修改为null)

/*Customer customer = new Customer();

customer.setCust_id(4l);

customer.setCust_name("梁如花");

session.update(customer);*/

// 2.先查询再修改.(推荐)

Customer customer = session.get(Customer.class, 4l);

customer.setCust_name("梁如花");

session.update(customer);

tx.commit();

session.close();

}

【Session删除某个对象的方法】

@Test

/**

 * 删除某个对象

 */

public void demo4(){

Session session = HibernateUtils.openSession();

Transaction tx = session.beginTransaction();

// 1.直接new 对象 删除

/*Customer customer = new Customer();

customer.setCust_id(2l);

session.delete(customer);*/

// 2.先查询,在删除(推荐)

Customer customer = session.get(Customer.class, 3l);

session.delete(customer);

tx.commit();

session.close();

}

1.2.4.4 Transaction:事务对象

Hibernate3的时候事务自动提交的参数是false(不自动提交)。Hibernate5可以自动提交,但是默认每个操作都是在一个事务中。一般需要手动开启事务。

commit();

rollback();

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值