Hibernate学习笔记01-入门

框架的概念

什么是框架

框架是指软件的半成品,它已经完成了软件的部分功能。

EE的三层架构

在这里插入图片描述

什么是Hibernate

是一个开放源码的对象关系映射框架,对JDBC进行非常轻量的对象封装,将POJO与数据库表建立映射关系,是一个全自动的orm框架,可以自动生成SQL语句,自动执行,可以应用于任何使用JDBC的场景

Hibernate是一个持久层的ORM框架
什么是ORM
ORM:对象关系映射,将一个对象与关系型数据库表建立一种映射,从而操作对象就是操作数据库中的表

Hibernate文件目录介绍

  • documentation :Hibernate开发的文档
  • lib:Hibernate开发包
    required:Hibernate开发的必须依赖包,在使用Hibernate时需要引用这里面的jar包(必须)
    optional:开发的必须依赖包,在使用Hibernate时需要引用这里面的jar包(可选)
  • project :Hibernate提供的项目

Hibernate的映射配置介绍

常用标签以及标签属性

标签 属性 作用
class 建立类与表的映射关系 name 需要映射的类的全路径
class 建立类与表的映射关系 table 与对象建立映射的数据库的全路径
id 建立类中的属性与表中的主键的对应关系 name 类中的属性名
id 建立类中的属性与表中的主键的对应关系 column 表中的字段名
id 建立类中的属性与表中的主键的对应关系 length 长度
id 建立类中的属性与表中的主键的对应关系 type 类型
property 建立类中中的普通属性与表字段对应的关系 name 类中的属性名
property 建立类中中的普通属性与表字段对应的关系 column 表中的字段名
property 建立类中中的普通属性与表字段对应的关系 length 长度
property 建立类中中的普通属性与表字段对应的关系 type 类型
property 建立类中中的普通属性与表字段对应的关系 not_null 设置非空
property 建立类中中的普通属性与表字段对应的关系 uniquer 设置唯一
类中的属性名与表中的字段名一致,可以省略column属性

Hibernate核心配置介绍

必须的配置

  • 必须的配置
    1.2 连接数据库的基本参数
    1.3方言配置
  • 可选配置
    2.1 hibernate.show_sql //打印SQl语句
    2.2 hibernate.format_sql //格式化打印的SQl语句
    2.3 自动建表:hibernate.hbm2ddl.auto
    2.3.1 none 不自动建表
    2.3.2 create 如果该表存在删除该表,重新建表,如果没有该表,就新建表
    2.3.3 create_drop 如果该表存在,删除该表,执行操作,再删除此表,如果没有该表,就新建表,使用完之后删除新建表
    2.3.4 update:更新表结构(如果表不存在则新建)
    2.3.5 validate:使用数据库中已有的表(不会新建,用于校验映射)
  • 映射文件的引入
    引入映射文件的位置
    <mapping resource="文件的完整路径"/>
  • 配置方式
    4.1 属性文件方式(Hibernate.properties)不能引入映射文件,需要手动编写代码加载映射文件
    4.2 XML文件方式(hibernate.cfg.xml) 常用

Hibernate的API

Configuration
加载核心配置文件
1.如果是属性文件
Configuration cfg = new Configuration();
2.如果是XML文件
Configuration cfg = new eConfiguration().configure();
3.手动加载映射
Configuration configuration = new eConfiguration().configure();
configuration.addResource("映射文件的完成路径") `

SessionFactroy
简介:初始化Hibernate,充当数据存储源的代理,负责建立Session对象,非轻量级
内部维护Hibernate的连接池,维护二级缓存,线程安全,一个项目只需要创建一个SessionFatroy
思考:c3p0的配置(配置C3P0连接池), 如何抽取工具类?
Session :类似Connection对象时连接对象
简介:负责执行被持久化对象的CRUD操作(与数据库交流,包含很多的常见的SQL语句),非线程安全,
代表的是Hibernate与数据库的连接对象,是与数据库对接的桥梁
Session的一些方法
因为Session不是线程安全的,所有只能将其定义为局部的
Session的API

  • 保存方法 Serializable save(Object obj)
  • 查询方法
    T get(Class c,Serializable id);
    T load(Class c,Serializable id)
        //* 1.加载配置文件
        Configuration cfg = new Configuration().configure();
        //* 2.创建SessionFactory对象,类似于JDBC中连接池
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        //* 3.获取Session对象
        Session session = sessionFactory.openSession();
        //* 4.手动开启事务
        Transaction transaction = session.beginTransaction();
        /*
         get方法采用的是立即加载,立即发送SQL语句去查询,查询后返回真实对象本身,查询一个找不到的对象就会返回Null
         load方法采用的是延迟加载,只有在真正使用这个对象时才发送SQL语句,查询后返回代理对象,询一个找不到的对象就会返回ObjectNotFountException
        */
        //* 5.代码编写
             //使用get方法查询
             Customer customer = session.get(Customer.class,1l)
        //* 6.事务提交
        transaction.commit();
        //* 7.释放资源
        session.close();
  • 修改方法 session.update(obj)
    两种使用方式
    1.直接创建对象,进行修改
//直接创建对象进行修改,不能获取数据源,所以会清掉原有记录的数据然后在将修改值写入
Customer customer = new Customer();
customer.setCust_id(1l);
customer.setcust_name("wangwu");
session.update(customer);

2.先查询在修改(推荐使用)

//先查询再修改,由于先查询所以获取到了数据源,所以不会清除其他字段数据,从而修改想要修改的内容
Customer customer = session.get(Customer.class,1l);
customer.setCust_name("mazi");
session.update(customer);
  • 删除方法 session.delete(obj)
    两种使用方式
    1.直接创建对象,进行删除
//直接创建对象进行修改,不能获取数据源,所以会清掉原有记录的数据然后在将修改值写入
Customer customer = new Customer();
customer.setCust_id(1l);
session.delete(customer);

2.先查询在删除(推荐使用)–级联删除

//先查询再修改,由于先查询所以获取到了数据源,所以不会清除其他字段数据,从而修改想要修改的内容
Customer customer = session.get(Customer.class,1l);
session.delete(customer);
  • 保存或更新(不常用) session.saveOrUpdate(obj)
    如果没有设置id那么就执行保存操作,设置id就会执行更新操作
    -查询所有 session.createQuery(“from 对象”)
Query query = session.createQuery("from customer");
 LIst<Customer> list = query.list();
for(Customer customer:list){
    System.out.priintln(custmoer);
}

案例——用户管理

jar包的引用

数据库驱动包
Hibernate开发必须引用的jar包
Hibernate引入日志记录包
在这里插入图片描述

实体类(Customer.java)

/**
 * @version 1.0
 * @autho ban
 * @abstract 用户实体类
 */
public class Customer {
    private Long cust_id;
    private String cust_name;

    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;
    }

log4j属性文件的编写 (log4j.properties)

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug

log4j.logger.org.hibernate.type=info

log4j.logger.org.hibernate.tool.hbm2ddl=debug

映射配置文件的编写(Customer.hbm.xml.tld)

 注意映射配置文件的命名规则为: 类名.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="net.zjitc.domain.Customer" table="cst_customer">
        <id name="cust_id" column="cust_id">
            <generator class="native"></generator>
        </id>
        <property name="cust_industry" column="cust_industry"></property>
        <property name="cust_level" column="cust_level"></property>
        <property name="cust_mobile" column="cust_mobile"></property>
        <property name="cust_name" column="cust_name"></property>
        <property name="cust_phone" column="cust_phone"></property>
        <property name="cust_source" column="cust_source"></property>
    </class>
</hibernate-mapping>

核心配置的编写

注意映射配置文件的命名规则为: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://localhost:3306/user</property>
        <!--数据库用户名-->
        <property name="hibernate.connection.username">ban</property>
        <!--数据库用户密码-->
        <property name="hibernate.connection.password">123456</property>
        <!--配置Hibernate的方言(即使用哪种数据库语言,这里使用的是MySQL)-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!--打印SQl语句,可选-->
        <property name="hibernate.show_sql">true</property>
        <!--格式化打印结果,可选-->
        <property name="hibernate.format_sql">true</property>
        <!--建立映射,必写,必须放在最后一行-->
        <mapping resource="Customer.hbm.xml.tld"/>
    </session-factory>
</hibernate-configuration>

测试类的编写

测试类可以对数据库进行CRUD操作

/**
 * @version 1.0
 * @autho ban
 * @date 2019/4/8 9:09
 */
public class HibernateDemo {
    public static void main(String[] args) {
        //* 1.加载配置文件
        Configuration cfg = new Configuration().configure();
        //* 2.创建SessionFactory对象,类似于JDBC中连接池
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        //* 3.获取Session对象
        Session session = sessionFactory.openSession();
        //* 4.手动开启事务
        Transaction transaction = session.beginTransaction();
        //* 5.代码编写
        Customer customer = new Customer();
        customer.setCust_name("zhangsan");
        session.save(customer);
        //* 6.事务提交
        transaction.commit();
        //* 7.释放资源
        session.close();

    }
}

抽取Hibernate工具类

/**
 * @version 1.0
 * @autho ban
 * @date 2019/4/8 9:09
 */
public class HibernateUtils {
    public static final Configuration cfg;
    public static final SessionFactory sf;
    static {
        cfg = new Configuration().configure();
        sf = cfg.buildSessionFactory();
    }

    public static Session openSession(){
        return sf.openSession();
    }
}

使用Hibernate工具类的测试类

测试类可以对数据库进行CRUD操作

/**
 * @version 1.0
 * @autho ban
 * @date 2019/4/8 9:09
 */
public class HibernateDemo {
    public static void main(String[] args) {
        Session session = HibernateUtils.openSession();
        Transaction bt = session.beginTransaction();
        
        Customer customer = new Customer();
        customer.setCust_name("lisi");
        session.save(customer);

        bt.commit();
        session.close();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43273271/article/details/89131469