【Hibernate】Re02 官网介绍

介绍:

创始人:Gavin King。EJB3.0专家,JBoss核心成员之一,《Hibernate In Action》作者

Hibernate是ORM的解决方案。

优点:

1、功能强大,减少代码量,提高持久化开发速度,降低维护成本
2、面向对象特点强调,组合,继承,多态
3、可移植性,即不依赖数据库的提供者,MySQL、Oracle、SqlServer只需要更换接口和配置文件即可运行
4、开源免费,允许改写源码,可扩展性好

缺点:

1、不适合大量使用存储过程的应用
2、不适合大规模批量的插入,修改,删除,内存消耗大

和Mybatis的对比:

Mybatis面向SQL-Mapping实现ORM
Hibernate面向对象实现ORM,对对象完善更多

Mybatis使用SQL语句,和数据库有关,移植性不如Hibernate,移植工作量大
Hibernate不关注SQL语句和结果映射,HQL与数据库无关

Mybatis直接使用SQL语句,灵活性相比Hibernate更好
Hibernate不适用关系模型设计不合理,不规范的系统,缓存也不如Mybatis

前言:

同时使用面向对象软件和关系数据库可能会很麻烦而且耗时。

由于对象和关系数据库中数据的表示方式不匹配,开发成本显著提高。

Hibernate是一个面向Java环境的对象/关系映射解决方案。

对象/关系映射是指将数据从对象模型表示映射到关系数据模型表示(反之亦然)的技术。

 

Hibernate不仅负责从Java类到数据库表(以及从Java数据类型到SQL数据类型)的映射,而且还提供数据查询和检索工具。

它可以显著减少开发时间,否则将花费在SQL和JDBC中的手动数据处理上。

 

Hibernate的设计目标是通过消除使用SQL和JDBC手工处理数据的需求,使开发人员从95%的与数据持久性相关的编程任务中解脱出来。

然而,与许多其他持久性解决方案不同,Hibernate并没有向您隐藏SQL的强大功能,并保证您在关系技术和知识方面的投资始终有效。

 

对于只使用存储过程实现数据库中的业务逻辑的以数据为中心的应用程序,Hibernate可能不是最好的解决方案,它对于基于Java的中间层中的面向对象的域模型和业务逻辑最有用。

然而,Hibernate当然可以帮助您删除或封装特定于供应商的SQL代码,并有助于完成从表格表示到对象图的结果集转换这一常见任务。

Preface
Working with both Object-Oriented software and Relational Databases can be cumbersome and time-consuming. 
Development costs are significantly higher due to a paradigm mismatch between how data is represented in objects versus relational databases.
Hibernate is an Object/Relational Mapping solution for Java environments.
The term Object/Relational Mapping refers to the technique of mapping data from an object model representation to a relational data model representation (and vice versa). Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities.
It can significantly reduce development
time otherwise spent with manual data handling in SQL and JDBC.

Hibernate’s design goal is to relieve the developer from 95% of common data persistence-related programming tasks by eliminating the need for manual, hand-crafted data processing using SQL and JDBC.
However, unlike many other persistence solutions, Hibernate does not hide the power of SQL from you and guarantees that your investment in relational technology and knowledge is as valid as always. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database,
it is most useful with object-oriented domain models and business logic in the Java-based middle-tier.
However, Hibernate can certainly help you to remove or encapsulate vendor-specific SQL code and will help with the common task of result set translation from a tabular representation to a graph of objects.

系统要求:

Hibernate5.2及更高版本至少需要Java1.8和JDBC4.2。

Hibernate5.1及更早版本至少需要Java1.6和JDBC4.0。

从源代码构建Hibernate5.1或更高版本时,由于JDK1.6编译器中存在错误,您需要Java1.7

原文:

System Requirements

Hibernate
5.2 and later versions require at least Java 1.8 and JDBC 4.2. Hibernate 5.1 and older versions require at least Java 1.6 and JDBC 4.0. When building Hibernate 5.1 or older from sources, you need Java 1.7 due to a bug in the JDK 1.6 compiler.

入门指南:

新用户可能想先浏览一下Hibernate入门指南,了解基本信息和教程。还有一系列专题指南,深入探讨各种主题。

快速入门地址:

https://docs.jboss.org/hibernate/orm/5.4/quickstart/html_single/

专题指南:

https://docs.jboss.org/hibernate/orm/5.4/topical/html_single/

原文:

Getting Started Guide
New users may want to first look through the Hibernate Getting Started Guide for basic information as well as tutorials. 
There is also a series of topical guides providing deep dives into various topics.

提示信息:

虽然使用Hibernate并不需要有很强的SQL背景,但它确实有很大帮助,因为它都归结为SQL语句。可能更重要的是理解数据建模原则。您可能需要将这些资源视为一个良好的起点:

数据建模维基百科定义

数据建模101

理解事务和设计模式(如工作单元(PoEAA)或应用程序事务的基础知识也很重要。这些主题将在文档中讨论,但事先了解肯定会有所帮助。

While having a strong background in SQL is not required to use Hibernate, it certainly helps a lot because it all boils down to SQL statements. 
Probably even more important is an understanding of data modeling principles.
You might want to consider these resources as a good starting point: Data modeling Wikipedia definition Data Modeling
101 Understanding the basics of transactions and design patterns such as Unit of Work (PoEAA) or Application Transaction are important as well.
These topics will be discussed
in the documentation, but a prior understanding will certainly help.

架构概况:

Hibernate作为一个ORM解决方案,有效地“位于”Java应用程序数据访问层和关系数据库之间,如上图所示。

Java应用程序使用hibernateapi来加载、存储、查询其域数据等。这里我们将介绍基本的hibernateapi。

这将是一个简短的介绍;我们稍后将详细讨论这些合同。 

作为一个JPA提供者,Hibernate实现了Java持久性API规范,JPA接口和Hibernate特定实现之间的关联可以在下图中看到:

Hibernate, as an ORM solution, effectively "sits between" the Java application data access layer and the Relational Database, as can be seen in the diagram above. 
The Java application makes use of the Hibernate APIs to load, store, query, etc. its domain data.

Here we will introduce the essential Hibernate APIs.
This will be a brief introduction; we will discuss these contracts in detail later. As a JPA provider, Hibernate implements the Java Persistence API specifications and the association between JPA interfaces and Hibernate specific implementations can be visualized in the following diagram:

会话工厂(org.hibernate.SessionFactory)

应用程序域模型到数据库的映射的线程安全(且不可变)表示。作为工厂org.hibernate.Session实例。EntityManagerFactory相当于一个SessionFactory,基本上,这两个集合在同一个SessionFactory实现中。

创建SessionFactory非常昂贵,因此,对于任何给定的数据库,应用程序应该只有一个关联的SessionFactory。

SessionFactory维护Hibernate跨所有会话使用的服务,例如二级缓存、连接池、事务系统集成等。

会话(org.hibernate.Session)

从概念上对“工作单元”(PoEAA)进行建模的单线程、短期对象。在JPA术语中,会话由EntityManager表示。

在幕后,Hibernate会话包装了一个JDBCjava.sql.Connection作为工厂org.hibernate.Transaction.事务实例。

它维护应用程序域模型的一般“可重复读取”持久性上下文(一级缓存)。 

事务(org.hibernate.Transaction)

应用程序用来划分单个物理事务边界的单线程、短期对象。

EntityTransaction是JPA的等价物,两者都充当抽象API,将应用程序与正在使用的底层事务系统(JDBC或JTA)隔离开来。

1、SessionFactory (org.hibernate.SessionFactory)
A thread-safe (and immutable) representation of the mapping of the application domain model to a database. 
Acts as a factory for org.hibernate.Session instances.
The EntityManagerFactory is the JPA equivalent of a SessionFactory and basically, those two converge into the same SessionFactory implementation. A SessionFactory is very expensive to create, so,
for any given database, the application should have only one associated SessionFactory.
The SessionFactory maintains services that Hibernate uses across all Session(s) such as second level caches, connection pools, transaction system integrations, etc. 2、Session (org.hibernate.Session) A single
-threaded, short-lived object conceptually modeling a "Unit of Work" (PoEAA).
In JPA nomenclature, the Session is represented by an EntityManager. Behind the scenes, the Hibernate Session wraps a JDBC java.sql.Connection and acts as a factory
for org.hibernate.Transaction instances.
It maintains a generally "repeatable read" persistence context (first level cache) of the application domain model. 3、Transaction (org.hibernate.Transaction) A single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries.
EntityTransaction is the JPA equivalent and both act as an abstraction API to isolate the application from the underlying transaction system in use (JDBC or JTA).

在案例中多了一个注册对象的销毁处理:

package cn.zeal4j;
import cn.zeal4j.domain.News;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.Test;
import java.io.Serializable;
import java.util.Date;

/**
 * @author Administrator
 * @file Hibernate
 * @create 2020 09 23 16:16
 */
public class HibernateTest {

    @Test
    public void quickStart() {
        Transaction transaction = null;
        Session session = null;
        SessionFactory sessionFactory = null;

        //  但在5.1.0版本汇总,hibernate则采用如下新方式获取:
        //  1. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为final
        //  在configure("cfg/hibernate.cfg.xml")方法中,如果不指定资源路径,默认在类路径下寻找名为hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate/hibernate.cfg.xml").build();

        try {


            //  2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();

            /* - - - - - - - 上面是配置准备,下面开始我们的数据库操作 - - - - - - - */
            session = sessionFactory.openSession(); //从会话工厂获取一个session

            transaction = session.beginTransaction();

            News news = new News(null, "新闻标题:这是一段演示文本...", "作者:Zeal4J", new Date());

            Serializable save = session.save(news);

            System.out.println("操作结果:" + save);

            transaction.commit();

        } catch (Exception exception) {
            exception.printStackTrace();
            transaction.rollback();
            // 通常情况会话工厂完成注册对象的销毁,但是会话工厂的建造出现异常,就需要手动销毁了
            StandardServiceRegistryBuilder.destroy(registry);
        } finally {
            session.close();
            sessionFactory.close();
        }
    }
}

 

posted @ 2020-09-23 22:27  emdzz  阅读(2061)  评论(0编辑  收藏  举报