数据持久化之Hibernate(07)

2017-05-23  本文已影响29人  小Q逛逛

Hibernate的使用

一. Hibernate HelloWorld

1.1 搭建Hibernate开发环境步骤

1. 导入jar包
antlr-2.7.6.jar
c3p0-0.9.1.2.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.1.12-bin.jar
slf4j-api-1.6.1.jar

2. 创建entity对象和对象的映射文件配置
Employee.java
Employee.hbm.xml

3. 在src/hibernate.cfg.xml 主配置文件下:
    数据库连接配置
    加载所有的的映射(*.hbm.xml)
4. 测试使用

Hello Hibernate的基本文件细节

创建数据库hibernate和表t_employee

CREATE TABLE `t_employee` (
  `empId` int(11) NOT NULL AUTO_INCREMENT,
  `empName` varchar(32) DEFAULT NULL,
  `workDate` date DEFAULT NULL,
  PRIMARY KEY (`empId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Employee.Java 实体类

package com.mrq.entity;

import java.util.Date;

public class Employee {
    private int empId;
    private String empName;
    private Date 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" 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 package="com.mrq.entity">
    <class name="Employee" table="t_employee">
        //主键
        <id name="empId" column="empId"></id>
        
        //非主键
        <property name="empName" column="empName"></property>
        <property name="workDate" column="workDate"></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:///hibernate?useUnicode=true&characterEncoding=utf8</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1l9o9v0e</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
    
    
        <mapping resource="com/mrq/entity/Employee.hbm.xml" />
    
    </session-factory>
    
</hibernate-configuration>


测试类 HibernateDemo.java

package com.mrq.main;

import java.util.Date;

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

import com.mrq.entity.Employee;

public class HibernateDemo {

    @Test
    public void testHibernate() {
        Employee employee = new Employee();
        employee.setEmpId(1);
        employee.setEmpName("工头2");
        employee.setWorkDate(new Date());
        //获取加载配置文件的管理类对象
        Configuration configuration = new Configuration();
        
        //加载默认路径的主配置文件
        configuration.configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        //开启事务
        Transaction tx = session.beginTransaction();
        session.save(employee);
        //提交事务
        tx.commit();
        
        //关闭
        session.close();
        sessionFactory.close();
    }
}

运行测试方法,数据会增加一条记录.

Hibernate的api

* Configuration: 配置管理类对象

    config.configure()加载主配置文件,默认路径src/  hibernate.cfg.xml
    config.buildSessionFactory()创建session工厂对象
    
* SessionFactory: session工厂类 (hibernate.cfg.xml文件的代表)
    sessionFactory.openSession();创建一个session对象
    sessionFactory.getCurrentSession();创建或者获取一个session对象
    
* Session : session对象维护了一个连接(Connection), 代表了与数据库连接的会话。Hibernate最重要的对象: 只用使用hibernate与数据库操作,都用到这个对象
    
    session.beginTransaction(); 开启一个事务; hibernate要求所有的与数据库的操作必须有事务的环境,否则报错!
    
    
* CRUD操作

    session.save(obj);   保存一个对象
    session.update(emp);  更新一个对象
    session.saveOrUpdate(emp);  保存或者更新的方法:
    1. 没有设置主键,执行保存;
    2. 有设置主键,执行更新操作; 
    3. 如果设置主键不存在报错!
                            
                            
* 主键查询:

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

* HQL查询:
    HQL查询与SQL查询区别:
        SQL: (结构化查询语句)查询的是表以及字段;  不区分大小写。
        HQL: hibernate  query  language 即hibernate提供的面向对象的查询语言
            查询的是对象以及对象的属性。
            区分大小写。

* Criteria查询:
     完全面向对象的查询。
    本地SQL查询:
        复杂的查询,就要使用原生态的sql查询,也可以,就是本地sql查询的支持!
        (缺点: 不能跨数据库平台!)

Hibernate的CRUD

EmployeeDaoImpl.java

package com.mrq.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.mrq.dao.EmployeeDao;
import com.mrq.entity.Employee;
import com.mrq.util.HibernateUtils;

public class EmployeeDaoImpl implements EmployeeDao {

    @Override
    public Employee findById(int id) {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Object object = session.get(Employee.class, id);
            return (Employee)object;
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

    @Override
    public List<Employee> getAll() {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query query = session.createQuery("from Employee");
            
            return query.list();
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

    @Override
    public List<Employee> getAll(String employeeName) {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query query = session.createQuery("from Employee where empName=?");
            query.setParameter(0, employeeName);
            return query.list();
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

    @Override
    public List<Employee> getAll(int index, int count) {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query query = session.createQuery("from Employee");
            query.setFirstResult(index); //查询的开始行数
            query.setMaxResults(count); //查询的记录总数
            List<Employee> list = query.list();
            return list;
            
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

    @Override
    public void save(Employee employee) {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            session.save(employee);
            
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

    @Override
    public void update(Employee employee) {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            session.update(employee);
            
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

    @Override
    public void delete(int id) {
        // TODO Auto-generated method stub
        Session session = null;
        Transaction tx = null;
        
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Object object = session.get(Employee.class, id);
            if (object!=null) {
                session.delete(object);
            }
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }finally {  
            
            if (session!=null) {
                if (tx!=null) {
                    tx.commit();
                }
                session.close();
            }
        }
    }

}

HibernateUtils.java

package com.mrq.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    private static SessionFactory sessionFactory;
    static{
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    
    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

二、Hibernate.cfg.xml 主配置

Hibernate.cfg.xml
主配置文件中主要配置:数据库连接信息、其他参数、映射信息!

常用配置查看源码:
hibernate-distribution-3.6.0.Final\project\etc\hibernate.properties

数据库连接参数配置
例如:
## MySQL

#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password


自动建表
Hibernate.properties

#hibernate.hbm2ddl.auto create-drop 每次在创建sessionFactory时候执行创建表;
                                当调用sesisonFactory的close方法的时候,删除表!
#hibernate.hbm2ddl.auto create   每次都重新建表; 如果表已经存在就先删除再创建
#hibernate.hbm2ddl.auto update  如果表不存在就创建; 表存在就不创建;
#hibernate.hbm2ddl.auto validate  (生成环境时候) 执行验证: 当映射文件的内容与数据库表结构不一样的时候就报错!


代码自动建表:
// 自动建表
    @Test
    public void testCreate() throws Exception {
        // 创建配置管理类对象
        Configuration config = new Configuration();
        // 加载主配置文件
        config.configure();
        
        // 创建工具类对象
        SchemaExport export = new SchemaExport(config);
        // 建表
        // 第一个参数: 是否在控制台打印建表语句
        // 第二个参数: 是否执行脚本
        export.create(true, true);
    }


三. 映射配置文件

1. 普通字段类型
2. 主键映射
    单列主键映射
    多列作为主键映射

主键生成策略,查看api:   5.1.2.2.1. Various additional generators


数据库:
    一个表能否有多个主键?   不能。
    为什么要设置主键?       数据库存储的数据都是有效的,必须保持唯一。

    (为什么把id作为主键?)
        因为表中通常找不到合适的列作为唯一列即主键,所以为了方法用id列,因为id是数据库系统维护可以保证唯一,所以就把这列作为主键!

    联合/复合主键
    如果找不到合适的列作为主键,除了用id列以外,我们一般用联合主键,即多列的值作为一个主键,从而确保记录的唯一性。

映射配置

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


<!-- 映射文件: 映射一个实体类对象;  描述一个对象最终实现可以直接保存对象数据到数据库中。  -->
<!-- 
    package: 要映射的对象所在的包(可选,如果不指定,此文件所有的类都要指定全路径)
    auto-import 默认为true, 在写hql的时候自动导入包名
                如果指定为false, 再写hql的时候必须要写上类的全名;
                  如:session.createQuery("from cn.itcast.c_hbm_config.Employee").list();
 -->
<hibernate-mapping package="com.mrq.hbm_config" auto-import="true">
    
    <!-- 
        class 映射某一个对象的(一般情况,一个对象写一个映射文件,即一个class节点)
            name 指定要映射的对象的类型
            table 指定对象对应的表;
                  如果没有指定表名,默认与对象名称一样 
     -->
    <class name="Employee" table="t_employee">
        
        <!-- 主键 ,映射-->
        <id name="empId" column="id">
            <!-- 
                主键的生成策略
                    identity  自增长(mysql,db2)
                    sequence  自增长(序列), oracle中自增长是以序列方法实现
                    native  自增长【会根据底层数据库自增长的方式选择identity或sequence】
                            如果是mysql数据库, 采用的自增长方式是identity
                            如果是oracle数据库, 使用sequence序列的方式实现自增长
                    
                    increment  自增长(会有并发访问的问题,一般在服务器集群环境使用会存在问题。)
                    
                    assigned  指定主键生成策略为手动指定主键的值
                    uuid      指定uuid随机生成的唯一的值
                    foreign   (外键的方式, one-to-one讲)
             -->
            <generator class="uuid"/>
        </id>
        
        <!-- 
            普通字段映射
            property
                name  指定对象的属性名称
                column 指定对象属性对应的表的字段名称,如果不写默认与对象属性一致。
                length 指定字符的长度, 默认为255
                type   指定映射表的字段的类型,如果不指定会匹配属性的类型
                    java类型:     必须写全名
                    hibernate类型:  直接写类型,都是小写
        -->
        <property name="empName" column="empName" type="java.lang.String" length="20"></property>
        <property name="workDate" type="java.util.Date"></property>
        <!-- 如果列名称为数据库关键字,需要用反引号或改列名。 -->
        <property name="desc" column="`desc`" type="java.lang.String"></property>
        
    </class>
    

</hibernate-mapping>

复合主键映射配置

// 复合主键类
public class CompositeKeys implements Serializable{
    private String userName;
    private String address;
   // .. get/set
}



public class User {

    // 名字跟地址,不会重复
    private CompositeKeys keys;
    private int age;
}

User.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.mrq.compositeKey" auto-import="true">
    
    <class name="User">
        
        <!-- 复合主键映射 -->
        <composite-id name="keys">
            <key-property name="userName" type="string"></key-property>
            <key-property name="address" type="string"></key-property>
        </composite-id>
        
        <property name="age" type="int"></property>     
        
    </class>
    

</hibernate-mapping>

测试类app.java

public class App {

    private static SessionFactory sf;
    static  {       
        // 创建sf对象
        sf = new Configuration()
            .configure()
            .addClass(User.class)  //(测试) 会自动加载映射文件:Employee.hbm.xml
            .buildSessionFactory();
    }

    //1. 保存对象
    @Test
    public void testSave() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        
        // 对象
        CompositeKeys keys = new CompositeKeys();
        keys.setAddress("广州天河");
        keys.setUserName("Jack");
        User user = new User();
        user.setAge(23);
        user.setKeys(keys);
        
        // 保存
        session.save(user);
        
        
        tx.commit();
        session.close();
    }
    
    @Test
    public void testGet() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        
        //构建主键再查询
        CompositeKeys keys = new CompositeKeys();
        keys.setAddress("广州天河");
        keys.setUserName("Jack");
        
        // 主键查询
        User user = (User) session.get(User.class, keys);
        // 测试输出
        if (user != null){
            System.out.println(user.getKeys().getUserName());
            System.out.println(user.getKeys().getAddress());
            System.out.println(user.getAge());
        }
        
        
        tx.commit();
        session.close();
    }
}

上一篇 下一篇

猜你喜欢

热点阅读