1. ORM概念

在学习 Hibernate 之前,我们先来了解ORM   对象关系映射

O, Object  对象

R,Realtion 关系  (关系型数据库: MySQL, Oracle…)

M,Mapping  映射

ORM, 解决什么问题?

           存储:   能否把对象的数据直接保存到数据库?

    获取:   能否直接从数据库拿到一个对象?

  想做到上面2点,必须要有映射

 

总结:

         Hibernate与ORM的关系?

            Hibernate是ORM的实现,简化对数据的操作。

2. Hibernate  HelloWorld案例

好 ,接下来熟悉的helloworld

首先,我们需要搭建Hibernate 环境

2.1 下载源码

 http://hibernate.org/orm/

    在这里我演示使用的版本:hibernate-distribution-3.6.0.Final

2.2  引入jar文件

我们 新建一个javaproject 项目 新建bin目录 导入jar

         hibernate3.jar核心  +  required 必须引入的(6个) +  jpa 目录  + 数据库驱动包

Hibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  ApiHibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  ApiHibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  ApiHibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  ApiHibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  Api

 

Hibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  ApiHibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  Api

 

2.3 写对象以及对象的映射

         Employee.java            对象

package com.yif.a_hello;

import java.util.Date;

public class Employee {
    private int empId;
    private String empName;
    private Date workDate;

    @Override
    public String toString() {
        return "Employee [empId=" + empId + ", empName=" + empName
                + ", workDate=" + workDate + "]";
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Date getWorkDate() {
        return workDate;
    }

    public void setWorkDate(Date workDate) {
        this.workDate = workDate;
    }
}

 

         Employee.hbm.xml        对象的映射 (映射文件)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.yif.a_hello">
    
    <class name="Employee" table="employee">
        
        <!-- 主键 ,映射-->
        <id name="empId" column="id">
            <generator class="native"/>
        </id>
        
        <!-- 非主键,映射 -->
        <property name="empName" column="empName"></property>
        <property name="workDate" column="workDate"></property>
        
    </class>

</hibernate-mapping>

 

2.4 hibernate.cfg.xml 主配置文件

         -à 数据库连接配置

         -à 加载所用的映射(*.hbm.xml)

<!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节点代表一个数据库 -->
    <session-factory>
    
        <!-- 1. 数据库连接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hib_demo?useUnicode=true&amp;characterEncoding=UTF8</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">密码</property>
        <!-- 
                数据库方法配置,hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
        -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- 2. 其他相关配置 -->
        <!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 2.2 格式化sql -->
        <property name="hibernate.format_sql">true</property>
        <!-- 2.3 自动建表  -->
        <property name="hibernate.hbm2ddl.auto">create</property>
        
        <!-- 3. 加载所有映射 -->
        <mapping resource="com/yif/a_hello/Employee.hbm.xml"/>
        
    </session-factory>
</hibernate-configuration>

 

2.5 App.java  测试

package com.yif.a_hello;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App {
    @Test
    public void testHello() throws Exception {
        // 对象
        Employee emp = new Employee();
        emp.setEmpName("Hello");
        emp.setWorkDate(new Date());
        
        // 获取加载配置文件的管理类对象
        Configuration config = new Configuration();
        config.configure();  // 默认加载src/hibenrate.cfg.xml文件
        // 创建session的工厂对象
        SessionFactory sf = config.buildSessionFactory();
        // 创建session (代表一个会话,与数据库连接的会话)
        Session session = sf.openSession();
        // 开启事务
        Transaction tx = session.beginTransaction();
        //保存-数据库
        session.save(emp);
        // 提交事务
        tx.commit();
        // 关闭
        session.close();
        sf.close();
    }
}

 

目录结构:

Hibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  Api

 

结果:

Hibernate框架 初识   ORM概念  搭建Hibernate环境  Hibernate  Api

该案例会自动创建表 ,因为主配置文件hibernate.cfg.xml 中

<!-- 2.3 自动建表  -->
        <property name="hibernate.hbm2ddl.auto">create</property> 后面会专门对主配置文件进行讲解。

3. Hibernate  Api

|-- Configuration       配置管理类对象

         config.configure();    加载主配置文件的方法(hibernate.cfg.xml)  默认加载src/hibernate.cfg.xml

         config.configure(“cn/config/hibernate.cfg.xml”);   加载指定路径下指定名称的主配置文件

         config.buildSessionFactory();   创建session的工厂对象

    sf = new Configuration().configure().buildSessionFactory();

 

|-- SessionFactory     session的工厂(或者说代表了这个hibernate.cfg.xml配置文件)

         sf.openSession();   创建一个sesison对象

         sf.getCurrentSession();  创建session或取出session对象

 

private static SessionFactory sf;
    static  {
        /*
        //1. 创建配置管理类对象
        Configuration config = new Configuration();
        // 加载配置文件  (默认加载src/hibernate.cfg.xml)
        config.configure();
        //2. 根据加载的配置管理类对象,创建SessionFactory对象
        sf = config.buildSessionFactory();
        */
        
        // 创建sf对象
        sf = new Configuration().configure().buildSessionFactory();
    }

 

3.1 Session 

session对象维护了一个连接(Connection), 代表了与数据库连接的会话。

  Hibernate最重要的对象: 只用使用hibernate与数据库操作,都用到这个对象

  session.beginTransaction(); 开启一个事务; hibernate要求所有的与数据库的操作必须有事务的环境,否则报错!

 

session.save(obj);   保存一个对象

//1. 保存对象
    @Test
    public void testSave() throws Exception {
        // 对象
        Employee emp = new Employee();
        emp.setEmpName("张三123");
        emp.setWorkDate(new Date());
        
        //根据session的工厂,创建session对象
        Session session = sf.openSession();
        // 开启事务
        Transaction tx = session.beginTransaction();
        //-----执行操作-----
        session.save(emp);
        
        // 提交事务/ 关闭
        tx.commit();
        session.close();
    }

session.update(emp);  更新一个对象

//更新
    @Test
    public void testUpdate() throws Exception {
        // 对象
        Employee emp = new Employee();
        emp.setEmpId(1);
        emp.setEmpName("修改");
        
        // 创建session
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        
        //-------执行操作-------
        // 没有设置主键,执行保存;有设置主键,执行更新操作; 如果设置主键不存在报错!
        session.saveOrUpdate(emp);
        
        tx.commit();
        session.close();
    }

session.saveOrUpdate(emp);  保存或者更新的方法:

  • 没有设置主键,执行保存;
  • 有设置主键,执行更新操作;
  • 如果设置主键不存在报错!

主键查询:

session.get(Employee.class, 1);    主键查询

session.load(Employee.class, 1);   主键查询 (支持懒加载)

 

3.2 HQL查询

         HQL查询与SQL查询区别:

                   SQL: (结构化查询语句)查询的是表以及字段;  不区分大小写。

                   HQL: hibernate  query  language 即hibernate提供的面向对象的查询语言

                            查询的是对象以及对象的属性。

                            区分大小写。

//HQL查询  【适合有数据库基础的】
    @Test
    public void testQuery() throws Exception {
        
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        
        // 主键查询
        //Employee emp = (Employee) session.get(Employee.class, 1);
        
        // HQL查询,查询全部
        Query q = session.createQuery("from Employee where empId=1 or empId=2");
        List<Employee> list = q.list();
        
        System.out.println(list);
        
        tx.commit();
        session.close();
    }

 

3.3 Criteria查询

          完全面向对象的查询。

//QBC查询  , query by criteria  完全面向对象的查询
    @Test
    public void testQBC() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        
        Criteria criteria = session.createCriteria(Employee.class);
        // 条件
        criteria.add(Restrictions.eq("empId", 1));
        // 查询全部
        List<Employee> list = criteria.list();
        
        System.out.println(list);
        
        tx.commit();
        session.close();
    }

 

3.4 本地SQL查询

         复杂的查询,就要使用原生态的sql查询,也可以,就是本地sql查询的支持!

         (缺点: 不能跨数据库平台!)

//sQL
    @Test
    public void testSQL() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        
        // 把每一行记录封装为对象数组,再添加到list集合
//        SQLQuery sqlQuery = session.createSQLQuery("select * from employee");
        // 把每一行记录封装为 指定的对象类型
        SQLQuery sqlQuery = session.createSQLQuery("select * from employee").addEntity(Employee.class);
        List list = sqlQuery.list();
        
        System.out.println(list);
        
        tx.commit();
        session.close();
    }

|-- Transaction    hibernate事务对象

 

4. Tag 

问题1:

         ClassNotFoundException…., 缺少jar文件!

问题2:

         如果程序执行程序,hibernate也有生成sql语句,但数据没有结果影响。

         问题一般是事务忘记提交…….

遇到问题,一定看错误提示!

相关文章:

  • 2021-05-26
  • 2021-08-17
  • 2021-05-31
  • 2021-08-01
  • 2021-10-12
  • 2021-12-02
猜你喜欢
  • 2021-11-09
  • 2021-07-26
  • 2021-09-18
  • 2021-10-22
  • 2021-12-01
  • 2021-10-12
  • 2022-02-21
相关资源
相似解决方案