1, Hibernate- entry

I. Overview

1. What is Hibernate:

Hibernate object-relational mapping framework is an open source, it had a very lightweight JDBC object package, it will POJO mapping relationship with a database table, is a fully automated orm framework, hibernate can automatically generate SQL statements, automatically, so that the Java programmer can use arbitrary object programming thinking to manipulate the database. Hibernate can be used in any occasion using JDBC, Java can be used in both client program can also be used in Servlet / JSP Web application, the most revolutionary is, Hibernate can replace the CMP in EJB applications in architecture JaveEE to complete the task of data persistence.

 

2. What is ORM:

ORM: Object Relational Mapping (Object-relational mapping). It refers to the establishment of a mapping between Java objects in a relational database table, so that the operator can manipulate objects on tables in the database.

 

3, Hibernate role:

1, objectification.

hibernate allows developers to object-oriented thinking to manipulate the database. jdbc only through SQL statements sent to the database metadata, data manipulation. And hibernate can be transformed metadata objects and at the bottom, so that the object-oriented developers only way to access the data.

2, more portable.

Use hibernate or JPA xml configuration and database dialects like mechanism, so that better portability hibernate, for different databases, developers need only operation can use the same data, without concern for differences between the database. The direct use of JDBC database would have to consider differences in question.

3, high development efficiency.

hibernate offers a number of packages (which is also its biggest drawback), a lot of data manipulation and relationships are so well packaged, developers do not need to write a lot of sql statement, which greatly improves the development of the developer effectiveness.

4, use caching mechanism.

hibernate provides a caching mechanism (session cache, L2 cache, query cache), for those little changes and frequently used data, they can be placed in the cache, each time you use does not have to go to query the database, caching mechanism improve performance boost.

                                                                   

 

 

 

 Second, create a project

1, download the hibernate directory:

                  

documentation: Documentation Hibernate development

lib: Hibernate Development Kit

 required: Hibernate development must dependencies

 optional: Hibernate development of alternative jar package

  project: the project provided by Hibernate

2, create a basic Java project, you can import the corresponding Jar.

                    

 

 

 

3. Create a table

The CREATE  TABLE `cst_customer` ( 
  ` cust_id` BIGINT ( 32 ) the NOT  NULL the AUTO_INCREMENT the COMMENT ' Customer ID (primary key) ' , 
  `cust_name` VARCHAR ( 32 ) the NOT  NULL the COMMENT ' Customer Name (company name) ' , 
  ` cust_source` VARCHAR ( 32 ) the DEFAULT  NULL the COMMENT ' customer information sources ' , 
  `cust_industry` VARCHAR ( 32 ) the DEFAULT  NULLThe COMMENT ' Customer Industries ' , 
  `cust_level` VARCHAR ( 32 ) the DEFAULT  NULL the COMMENT ' customer level ' , 
  ` cust_phone` VARCHAR ( 64 ) the DEFAULT  NULL the COMMENT ' landline ' , 
  `cust_mobile` VARCHAR ( 16 ) the DEFAULT  NULL the COMMENT ' mobile phone ' ,
   a PRIMARY  KEY ( `cust_id`) 
) ENGINE = the InnoDB the AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 

 

4, create the corresponding entity class

Package Penalty for com.turtle.dao; 

Import the java.io.Serializable; 

public  class the Customer the implements Serializable { 

    // customer number (primary key) 
    Private Long cust_id;
     // Customer Name (Company Name) 
    Private String CUST_NAME;
     // customer information sources 
    Private String cust_source;
     // customer industries 
    Private String cust_industry;
     // customer level 
    Private String cust_level;
     // fixed-line telephone 
    Private String cust_phone;
     // mobile 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;
    }
}

 

 

5, create a map

Mapping needs to be done through XML configuration file, the configuration file can be named. Try unified naming convention (class name .hbm.xml)

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE Hibernate-Mapping the PUBLIC 
        "- // Hibernate / Hibernate Mapping DTD 3.0 // EN" 
        "http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd " > 
< Hibernate-mapping > 
    <-! a mapping table of the class -> 
    < class name =" com.turtle.dao.Customer " table =" cst_customer " > 
        <! - - primary key associating class attribute table -> 
        < ID name = "the cust_id" column = "the cust_id"  > 
            <generator class="native"/>
        </id>

        <!-- 建立类中的普通的属性和表的字段的对应 -->
        <property name="cust_name" column="cust_name" length="32" />
        <property name="cust_source" column="cust_source" length="32"/>
        <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>

 

[Label] configuration class

  Tag is used to establish the mapping classes and tables

  Attributes:

  Class full path: name

  table: table name (the class name and the same table name, table may be omitted)

  catalog: database name

 

Configuration id [label]

  Tag is used to establish corresponding relationship between the primary key class attribute table

  Attributes:

  name: class attribute name

  column: field names of the table (attribute names and field names class table if they are consistent, column may be omitted)

  length: length

  type: Type

 

[Label] configuration property

  Tag is used to establish a corresponding relationship field common class attribute table

  Attributes:

  name: class attribute name

  column: field names in the table

  length: length

  type: Type

  not-null: non-empty set

  unique: a unique setting

 

6, create a Hibernate core configuration file

Name Hibernate core configuration file: 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_demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!-- 配置Hibernate的方言 -->
        <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>
        <!-- 自动创建表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 配置C3P0连接池 -->
        <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.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>

        <mapping resource="com/turtle/dao/Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 

  必须的配置

    连接数据库的基本的参数

    驱动类

    url路径

    用户名

    密码

    方言

 可选的配置

   显示SQL          :hibernate.show_sql

    格式化SQL     :hibernate.format_sql

    自动建表        :hibernate.hbm2ddl.auto

      none                 :不使用hibernate的自动建表

      create               :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)

      create-drop     :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)

      update             :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)

     validate            :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。

 映射文件的引入    

    引入映射文件的位置

  <mapping resource="com/turtle/dao/Customer.hbm.xml"/>

 

7、编写测试代码

package com.turtle.test;

import com.turtle.dao.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class TestCustomer {
    public static  void main(String [] args){
        // 1、加载配置文件
        Configuration configuration = new Configuration().configure();
        // 2、创建一个SessionFactory对象
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 3、创建Session对象
        Session session = sessionFactory.openSession();
        // 4、开启事务
        Transaction transaction = session.beginTransaction();
        try{
            Customer customer = new Customer();
            customer.setCust_name("测试用户1");
            // 调用Hibernate自带的API来进行保存操作
            session.save(customer);
            // 提交事务
            transaction.commit();
        }catch (Exception e){
            e.printStackTrace();
            // 回滚事务
            transaction.rollback();
        }finally {
            // 关闭连接
            session.close();
        }
    }
}

 

 8、控制台打印的SQL语句和数据的结果表数据

                                                                          

 

                                                                          

三、Hibernate的API

1、Configuration:Hibernate的配置对象

  作用:加载核心配置文件

 

hibernate.properties

Configuration cfg = new Configuration();

 

 hibernate.cfg.xml

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

  加载映射文件

 

// 手动加载映射

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

 

2、 SessionFactory:Session工厂

SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存(不讲)。是线程安全的对象。一个项目创建一个对象即可。

 

3、Session:类似Connection对象是连接对象

Session代表的是Hibernate与数据库的链接对象。不是线程安全的。与数据库交互桥梁。

  Session中的API

  保存方法:

    Serializable save(Object obj);

  查询方法:

    T get(Class c,Serializable id);

    T load(Class c,Serializable id);

  修改方法

   void update(Object obj);

  删除方法

    void delete(Object obj);s

  保存或更新

    void saveOrUpdate(Object obj)

 

4、  Transaction:事务对象

Hibernate中管理事务的对象。

    commit();

    rollback();

 

Guess you like

Origin www.cnblogs.com/zhh19981104/p/11829150.html