初学者的Hibernate教程

欢迎来到初学者的Hibernate教程。Hibernate是最广泛使用的Java ORM工具之一。大多数应用程序使用关系数据库存储应用程序信息,在低级别上,我们使用JDBC API连接到数据库并执行CRUD操作。

初学者Hibernate教程

如果您查看JDBC代码,会发现有很多样板代码,存在资源泄漏和数据不一致的可能性,因为所有工作都需要开发人员完成。这就是ORM工具派上用场的地方。对象关系映射ORM是将应用程序域模型对象映射到关系数据库表的编程技术。Hibernate是基于Java的ORM工具,提供了将应用程序域对象映射到关系数据库表以及反之的框架。使用Hibernate作为ORM工具的一些好处包括:

  1. Hibernate支持将Java类映射到数据库表以及反之。它提供了在所有主要关系数据库上执行CRUD操作的功能。
  2. Hibernate消除了与JDBC一起使用时产生的所有样板代码,并负责管理资源,因此我们可以专注于业务用例,而不是确保数据库操作不会导致资源泄漏。
  3. Hibernate支持事务管理,并确保系统中没有不一致的数据。
  4. 由于我们使用XML、属性文件或注解来将Java类映射到数据库表,它在应用程序和数据库之间提供了一个抽象层。
  5. Hibernate帮助我们映射连接、集合、继承对象,我们可以轻松可视化我们的模型类如何表示数据库表。
  6. Hibernate提供了强大的查询语言(HQL),类似于SQL。但是,HQL是完全面向对象的,并理解继承、多态和关联等概念。
  7. Hibernate还与一些外部模块集成。例如,Hibernate Validator是Bean验证(JSR 303)的参考实现。
  8. Hibernate是Red Hat社区的开源项目,被全球广泛使用。这使它比其他选择更好,因为学习曲线小,有大量的在线文档,并且在论坛中很容易找到帮助。
  9. Hibernate易于与其他Java EE框架集成,它如此受欢迎以至于Spring框架提供了与Spring应用程序集成Hibernate的内置支持。

I hope all the above benefits will convince you that Hibernate is the best choice for your application object-relational mapping requirements. Let’s look at the Hibernate Framework architecture now and then we will jump into sample project where we will look into different ways to configure Hibernate in standalone java application and use it.

Hibernate架构

下图显示了Hibernate架构以及它作为应用程序类和JDBC/JTA API之间的抽象层如何工作。清楚地表明了Hibernate是建立在JDBC和JTA API之上的。让我们逐一看看Hibernate架构的核心组件。

  • SessionFactory(org.hibernate.SessionFactory):SessionFactory是一个不可变的、线程安全的缓存,用于单个数据库的已编译映射。我们可以使用SessionFactory获取org.hibernate.Session的实例。
  • Session(org.hibernate.Session):Session是一个单线程、短暂的对象,表示应用程序与持久存储之间的对话。它包装了JDBC的java.sql.Connection,并作为org.hibernate.Transaction的工厂。
  • 持久化对象:持久化对象是短暂的、单线程的对象,包含持久状态和业务功能。它们可以是普通的JavaBeans/POJOs,并且与一个org.hibernate.Session关联。
  • **瞬时对象**:瞬时对象是持久化类的实例,目前尚未与org.hibernate.Session关联。它们可能是由应用程序实例化但尚未持久化,或者是由已关闭的org.hibernate.Session实例化的。
  • **事务(org.hibernate.Transaction)**:事务是应用程序用于指定原子工作单元的单线程、短暂的对象。它将应用程序与底层的JDBC或JTA事务抽象开来。在某些情况下,一个org.hibernate.Session可能跨越多个org.hibernate.Transaction
  • **连接提供者(org.hibernate.connection.ConnectionProvider)**:连接提供者是JDBC连接的工厂。它在应用程序和底层的javax.sql.DataSourcejava.sql.DriverManager之间提供了抽象。它不会暴露给应用程序,但可以由开发人员进行扩展。
  • **事务工厂(org.hibernate.TransactionFactory)**:用于创建org.hibernate.Transaction实例的工厂。

**Hibernate和Java持久化API(JPA)**

Hibernate提供了Java持久化API的实现,因此我们可以在模型Bean中使用JPA注解,而Hibernate会负责配置以便在CRUD操作中使用它。我们将通过注解示例来看这个。

Hibernate示例

在开发Hibernate应用程序时,我们需要提供两套配置。第一套配置包含特定于数据库的属性,将用于创建数据库连接和Session对象。第二套配置包含模型类与数据库表之间的映射。我们可以使用基于XML或基于属性的配置来配置与数据库连接相关的配置。我们可以使用基于XML或基于注解的配置来提供模型类和数据库表的映射。我们将使用来自javax.persistence的JPA注解进行基于注解的映射。我们的最终项目将如下图所示。 在Eclipse或您喜欢的IDE中创建一个Maven项目,您可以使用任何您喜欢的名称。在我们继续项目的不同组件之前,我们需要进行数据库设置。

数据库表设置

对于我的示例,我正在使用MySQL数据库,下面的脚本用于创建必要的表格。

CREATE TABLE `Employee` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `role` varchar(20) DEFAULT NULL,
  `insert_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

请注意,员工表中的“id”列是由MySQL自动生成的,因此我们不需要插入它。

Hibernate项目依赖项

我们最终的pom.xml文件如下所示。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.journaldev.hibernate</groupId>
  <artifactId>HibernateExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>HibernateExample</name>
  
  <dependencies>
  	<dependency>
  		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate-core</artifactId>
  		<version>4.3.5.Final</version>
  	</dependency>
  	<!-- Hibernate 4 uses Jboss logging, but older versions slf4j for logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
        	<groupId>mysql</groupId>
        	<artifactId>mysql-connector-java</artifactId>
        	<version>5.0.5</version>
        </dependency>
  </dependencies>
  
  <build>
  	<finalName>${project.artifactId}</finalName>
  </build>
</project>

hibernate-core构件包含所有核心的Hibernate类,因此通过在项目中包含它,我们将获得所有必要的功能。请注意,我正在使用最新的Hibernate版本(4.3.5.Final)作为示例项目,并且Hibernate仍在不断发展,我已经看到每个主要版本发布时都会有许多核心类发生变化。因此,如果您使用的是其他版本,则有可能必须修改Hibernate配置才能使其正常工作。但是,我确信它将适用于所有4.x.x版本。Hibernate 4使用JBoss日志记录,但旧版本使用slf4j进行日志记录,因此我已经在我的项目中包含了slf4j-simple构件,尽管因为我正在使用Hibernate 4而不是必需的。mysql-connector-java是连接到MySQL数据库的MySQL驱动程序,如果您使用其他数据库,则添加相应的驱动程序构件。

域模型类

正如您在上面的图片中所看到的,我们有两个模型类,EmployeeEmployee1。Employee 是一个简单的 Java Bean 类,我们将使用基于 XML 的配置来提供其映射细节。Employee1 是一个 Java Bean,其中的字段带有 JPA 注解,因此我们不需要在单独的 XML 文件中提供映射。

package com.journaldev.hibernate.model;

import java.util.Date;

public class Employee {

	private int id;
	private String name;
	private String role;
	private Date insertTime;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public Date getInsertTime() {
		return insertTime;
	}
	public void setInsertTime(Date insertTime) {
		this.insertTime = insertTime;
	}
	
}

Employee 类是简单的 Java Bean,这里没有什么特别需要讨论的。

package com.journaldev.hibernate.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name="Employee", 
	   uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
public class Employee1 {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="ID", nullable=false, unique=true, length=11)
	private int id;
	
	@Column(name="NAME", length=20, nullable=true)
	private String name;
	
	@Column(name="ROLE", length=20, nullable=true)
	private String role;
	
	@Column(name="insert_time", nullable=true)
	private Date insertTime;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public Date getInsertTime() {
		return insertTime;
	}
	public void setInsertTime(Date insertTime) {
		this.insertTime = insertTime;
	}
}

javax.persistence.Entity 注解用于将一个类标记为 Entity Bean,可以由 Hibernate 持久化,因为 Hibernate 提供了 JPA 实现。 javax.persistence.Table 注解用于定义表映射和列的唯一约束。 javax.persistence.Id 注解用于定义表的主键。 javax.persistence.GeneratedValue 用于定义字段将自动生成,采用 GenerationType.IDENTITY 策略,以便生成的“id”值映射到 Bean,并可以在 Java 程序中检索到。 javax.persistence.Column 用于将字段映射到表列,我们还可以为 Bean 属性指定长度、可为空性和唯一性。

Hibernate映射XML配置

如上所述,我们将使用基于XML的配置来进行Employee类的映射。我们可以选择任何名称,但最好选择与表或Java bean名称相匹配以增加清晰度。我们的Hibernate映射文件的Employee bean看起来如下。employee.hbm.xml

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

<hibernate-mapping>
	<class name="com.journaldev.hibernate.model.Employee" table="EMPLOYEE">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="role" type="java.lang.String">
            <column name="ROLE" />
        </property>
        <property name="insertTime" type="timestamp">
        	<column name="insert_time" />
        </property>
    </class>
</hibernate-mapping>

XML配置简单且与基于注释的配置执行相同的操作。

Hibernate配置文件

我们将创建两个Hibernate配置XML文件 – 一个用于基于XML的配置,另一个用于基于注释的配置。hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Database connection properties - Driver, URL, user, password -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
		<property name="hibernate.connection.username">pankaj</property>
		<property name="hibernate.connection.password">pankaj123</property>
		<!-- Connection Pool Size -->
		<property name="hibernate.connection.pool_size">1</property>
		
		<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
		<property name="hibernate.current_session_context_class">thread</property>
		
		<!-- Outputs the SQL queries, should be disabled in Production -->
		<property name="hibernate.show_sql">true</property>
		
		<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
			Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 

		<!-- mapping file, we can use Bean annotations too --> 
		<mapping resource="employee.hbm.xml" />
	</session-factory>
</hibernate-configuration>

大多数属性与数据库配置相关,其他属性细节在注释中给出。请注意Hibernate映射文件的配置,我们可以定义多个Hibernate映射文件并在此处进行配置。还要注意,映射是特定于会话工厂的。hibernate-annotation.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Database connection properties - Driver, URL, user, password -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
		<property name="hibernate.connection.username">pankaj</property>
		<property name="hibernate.connection.password">pankaj123</property>
		
		<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
		<property name="hibernate.current_session_context_class">thread</property>
		
		<!-- Mapping with model class containing annotations -->
		<mapping class="com.journaldev.hibernate.model.Employee1"/>
	</session-factory>
</hibernate-configuration>

大多数配置与基于XML的配置相同,唯一的区别在于映射配置。我们既可以为类提供映射配置,也可以为包提供映射配置。

Hibernate SessionFactory

I have created a utility class where I am creating SessionFactory from XML based configuration as well as property based configuration. For property based configuration, we could have a property file and read it in the class, but for simplicity I am creating Properties instance in the class itself.

package com.journaldev.hibernate.util;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.journaldev.hibernate.model.Employee1;

public class HibernateUtil {

	//基于XML的配置
	private static SessionFactory sessionFactory;
	
	//基于注解的配置
	private static SessionFactory sessionAnnotationFactory;
	
	//基于属性的配置
	private static SessionFactory sessionJavaConfigFactory;

    private static SessionFactory buildSessionFactory() {
        try {
            //从hibernate.cfg.xml文件创建SessionFactory
        	Configuration configuration = new Configuration();
        	configuration.configure("hibernate.cfg.xml");
        	System.out.println("Hibernate Configuration loaded");
        	
        	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        	System.out.println("Hibernate serviceRegistry created");
        	
        	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        	
            return sessionFactory;
        }
        catch (Throwable ex) {
            //确保记录异常,因为可能会被吞噬
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private static SessionFactory buildSessionAnnotationFactory() {
    	try {
            //从hibernate.cfg.xml文件创建SessionFactory
        	Configuration configuration = new Configuration();
        	configuration.configure("hibernate-annotation.cfg.xml");
        	System.out.println("Hibernate Annotation Configuration loaded");
        	
        	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        	System.out.println("Hibernate Annotation serviceRegistry created");
        	
        	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        	
            return sessionFactory;
        }
        catch (Throwable ex) {
            //确保记录异常,因为可能会被吞噬
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
	}

    private static SessionFactory buildSessionJavaConfigFactory() {
    	try {
    	Configuration configuration = new Configuration();
		
		//创建属性,也可以从属性文件中读取
		Properties props = new Properties();
		props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
		props.put("hibernate.connection.url", "jdbc:mysql://localhost/TestDB");
		props.put("hibernate.connection.username", "pankaj");
		props.put("hibernate.connection.password", "pankaj123");
		props.put("hibernate.current_session_context_class", "thread");
		
		configuration.setProperties(props);
		
		//我们可以设置映射文件或带注解的类
		//addClass(Employee1.class)将查找资源
		//com/journaldev/hibernate/model/Employee1.hbm.xml(不好)
		configuration.addAnnotatedClass(Employee1.class);
		
		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    	System.out.println("Hibernate Java Config serviceRegistry created");
    	
    	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    	
        return sessionFactory;
    	}
        catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
	}
    
	public static SessionFactory getSessionFactory() {
		if(sessionFactory == null) sessionFactory = buildSessionFactory();
        return sessionFactory;
    }
	
	public static SessionFactory getSessionAnnotationFactory() {
		if(sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
        return sessionAnnotationFactory;
    }
	
	public static SessionFactory getSessionJavaConfigFactory() {
		if(sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
        return sessionJavaConfigFactory;
    }
	
}

基于XML的配置和基于注解的配置创建SessionFactory的过程相同。对于基于属性的配置,我们需要在创建SessionFactory之前在Configuration对象中设置属性并添加注解类。总体而言,创建SessionFactory包括以下步骤:

  1. 创建Configuration对象并对其进行配置
  2. 创建ServiceRegistry对象并应用配置设置。
  3. 使用configuration.buildSessionFactory()通过将ServiceRegistry对象作为参数传递来获取SessionFactory对象。

我们的应用程序现在几乎准备好了,让我们编写一些测试程序并执行它们。

Hibernate XML 配置测试

我们的测试程序如下所示。

package com.journaldev.hibernate.main;

import java.util.Date;

import org.hibernate.Session;

import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateMain {

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.setName("Pankaj");
		emp.setRole("CEO");
		emp.setInsertTime(new Date());
		
		//获取 Session
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		//开始事务
		session.beginTransaction();
		//保存模型对象
		session.save(emp);
		//提交事务
		session.getTransaction().commit();
		System.out.println("Employee ID="+emp.getId());
		
		//终止会话工厂,否则程序将无法结束
		HibernateUtil.getSessionFactory().close();
	}

}

程序是自解释的,当我们执行测试程序时,我们会得到以下输出。

May 06, 2014 12:40:06 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 06, 2014 12:40:06 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 06, 2014 12:40:06 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 06, 2014 12:40:06 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
May 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
May 06, 2014 12:40:07 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: employee.hbm.xml
May 06, 2014 12:40:08 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Configuration loaded
Hibernate serviceRegistry created
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 06, 2014 12:40:08 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 06, 2014 12:40:08 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 06, 2014 12:40:08 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select max(ID) from EMPLOYEE
Hibernate: insert into EMPLOYEE (NAME, ROLE, insert_time, ID) values (?, ?, ?, ?)
Employee ID=19
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

请注意,它打印了生成的员工 ID,您可以检查数据库表来确认。

Hibernate 注解配置测试

package com.journaldev.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.journaldev.hibernate.model.Employee1;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateAnnotationMain {

	public static void main(String[] args) {
		Employee1 emp = new Employee1();
		emp.setName("David");
		emp.setRole("Developer");
		emp.setInsertTime(new Date());
		
		//获取 Session
		SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
		Session session = sessionFactory.getCurrentSession();
		//开始事务
		session.beginTransaction();
		//保存模型对象
		session.save(emp);
		//提交事务
		session.getTransaction().commit();
		System.out.println("Employee ID="+emp.getId());
		
		//终止会话工厂,否则程序将无法结束
		sessionFactory.close();
	}

}

当我们执行以上程序时,我们得到以下输出。

May 06, 2014 12:42:22 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 06, 2014 12:42:22 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 06, 2014 12:42:22 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 06, 2014 12:42:22 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate-annotation.cfg.xml
May 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate-annotation.cfg.xml
May 06, 2014 12:42:23 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Annotation Configuration loaded
Hibernate Annotation serviceRegistry created
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 06, 2014 12:42:23 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 06, 2014 12:42:23 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 06, 2014 12:42:23 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee ID=20
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

请查看输出并将其与基于XML的配置输出进行比较,您会注意到一些差异。例如,我们没有为基于注解的配置设置连接池大小,因此它被设置为默认值20。

Hibernate Java配置测试

package com.journaldev.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.journaldev.hibernate.model.Employee1;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateJavaConfigMain {

	public static void main(String[] args) {
		Employee1 emp = new Employee1();
		emp.setName("Lisa");
		emp.setRole("Manager");
		emp.setInsertTime(new Date());
		
		//获取会话
		SessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();
		Session session = sessionFactory.getCurrentSession();
		//开始事务
		session.beginTransaction();
		//保存模型对象
		session.save(emp);
		//提交事务
		session.getTransaction().commit();
		System.out.println("Employee ID="+emp.getId());
		
		//终止会话工厂,否则程序将无法结束
		sessionFactory.close();
	}

}

上述测试程序的输出如下:

May 06, 2014 12:45:09 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 06, 2014 12:45:09 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 06, 2014 12:45:09 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 06, 2014 12:45:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Hibernate Java Config serviceRegistry created
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 06, 2014 12:45:10 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
May 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 06, 2014 12:45:10 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 06, 2014 12:45:10 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee ID=21
May 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

这就是初学者Hibernate教程的全部内容,我希望这足以让您开始。我们将在未来的教程中深入了解Hibernate框架的不同特性。从下面的链接下载完整的项目,并进行更多的实践以获取更多知识。

下载Hibernate初学者项目

Source:
https://www.digitalocean.com/community/tutorials/hibernate-tutorial-for-beginners