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

1. ORM概念

在学习 Hibernate 以前,咱们先来了解ORM   对象关系映射java

O, Object  对象mysql

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

M,Mapping  映射数据库

ORM, 解决什么问题?数组

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

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

  想作到上面2点,必需要有映射ide

 

总结:学习

         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 目录  + 数据库驱动包

 

 

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.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语句,但数据没有结果影响。

         问题通常是事务忘记提交…….

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

相关文章
相关标签/搜索