Hibernate教程
欢迎使用面向的Hibernate教程。
Hibernate是使用最广泛的Java ORM工具之一。
大多数应用程序使用关系数据库来存储应用程序信息,而在底层,我们使用JDBC API来连接数据库并执行CRUD操作。
Hibernate 教程
如果您查看JDBC代码,那么会有很多样板代码,并且有资源泄漏和数据不一致的可能性,因为所有工作都需要开发人员来完成。
这是ORM工具派上用场的地方。
对象关系映射或者对象关系管理(ORM)是将应用程序域模型对象映射到关系数据库表的编程技术。
Hibernate是基于Java的ORM工具,它提供了将应用程序域对象映射到关系数据库表以及反之亦然的框架。
使用Hibernate作为ORM工具的一些好处是:
Hibernate支持将Java类映射到数据库表,反之亦然。
它提供了在所有主要关系数据库中执行CRUD操作的功能。Hibernate消除了JDBC附带的所有样板代码,并负责管理资源,因此我们可以专注于业务用例,而不是确保数据库操作不会引起资源泄漏。
Hibernate支持事务管理,并确保系统中没有不一致的数据。
由于我们使用XML,属性文件或者注释将Java类映射到数据库表,因此它在应用程序和数据库之间提供了一个抽象层。
Hibernate帮助我们映射联接,集合,继承对象,并且我们可以轻松地可视化模型类如何表示数据库表。
Hibernate提供了类似于SQL的强大查询语言(HQL)。
但是,HQL完全面向对象,并且了解诸如继承,多态性和关联之类的概念。Hibernate还提供了与某些外部模块的集成。
例如,Hibernate Validator是Bean验证(JSR 303)的参考实现。Hibernate是Red Hat Community的一个开源项目,已在全球范围内使用。
与其他方法相比,这是一个更好的选择,因为学习曲线很小,并且有大量的在线文档,并且可以在论坛中轻松获得帮助。Hibernate易于与其他Java EE框架集成,因此非常流行,Spring框架提供了将Hibernate与Spring应用程序集成的内置支持。
希望以上所有优点都能使您确信Hibernate是满足应用程序对象关系映射要求的最佳选择。
现在让我们看一下Hibernate Framework架构,然后进入示例项目,在此我们将探讨在独立的Java应用程序中配置Hibernate并使用它的不同方法。
Hibernate 架构
下图显示了Hibernate体系结构以及它如何充当应用程序类和JDBC/JTA API之间的抽象层以进行数据库操作。
很明显,Hibernate是基于JDBC和JTA API构建的。
让我们一一介绍一下Hibernate 架构的核心组件。
SessionFactory(org.hibernate.SessionFactory):SessionFactory是单个数据库的已编译映射的不可变线程安全缓存。
我们可以使用SessionFactory来获取org.hibernate.Session的实例。会话(org.hibernate.Session):会话是一个单线程,短暂的对象,表示应用程序与持久性存储之间的对话。
它包装了JDBC java.sql.Connection,并作为org.hibernate.Transaction的工厂。持久对象:持久对象是包含持久状态和业务功能的短寿命单线程对象。
这些可以是普通的JavaBeans/POJO。
它们与一个org.hibernate.Session关联。瞬时对象:瞬时对象是当前未与org.hibernate.Session关联的持久类实例。
它们可能已由应用程序实例化,但尚未持久化,或者它们可能已由封闭的org.hibernate.Session实例化。事务(org.hibernate.Transaction):事务是应用程序用来指定原子工作单元的单线程,短期对象。
它将应用程序从底层JDBC或者JTA事务中抽象出来。
在某些情况下,一个org.hibernate.Session可能跨越多个org.hibernate.Transaction。ConnectionProvider(org.hibernate.connection.ConnectionProvider):ConnectionProvider是JDBC连接的工厂。
它提供了应用程序和基础javax.sql.DataSource或者java.sql.DriverManager之间的抽象。
它没有公开给应用程序,但是可以由开发人员扩展。TransactionFactory(org.hibernate.TransactionFactory):一个用于org.hibernate.Transaction实例的工厂。
Hibernate和Java Persistence API(JPA)
Hibernate提供了Java Persistence API的实现,因此我们可以将JPA注释与模型bean一起使用,并且hibernate将负责配置它以便在CRUD操作中使用。
我们将通过注释示例对此进行研究。
Hibernate 示例
在开发Hibernate 应用程序时,我们需要提供两组配置。
第一组配置包含特定于数据库的属性,这些属性将用于创建数据库连接和会话对象。
第二组配置包含模型类和数据库表之间的映射。
我们可以将基于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;
注意,Employee表的" 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.theitroad.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驱动程序,如果您正在使用任何其他数据库,则添加相应的驱动程序构件。
领域模型类
如上图所示,我们有两个模型类,即" Employee"和" Employee1"。
Employee是一个简单的Java Bean类,我们将使用基于XML的配置来提供其映射详细信息。
Employee1是一个Java Bean,其中用JPA注释对字段进行注释,因此我们不需要在单独的XML文件中提供映射。
package com.theitroad.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.theitroad.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"批注用于将类标记为可被hibernate保留的Entity bean,因为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名称。
我们用于Employee bean的Hibernate 映射文件如下所示。
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.theitroad.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">hyman</property> <property name="hibernate.connection.password">hyman123</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">hyman</property> <property name="hibernate.connection.password">hyman123</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.theitroad.hibernate.model.Employee1" </session-factory> </hibernate-configuration>
大多数配置与基于XML的配置相同,唯一的区别是映射配置。
我们可以提供类和包的映射配置。
Hibernate 会话工厂
我创建了一个实用程序类,在该类中,我将从基于XML的配置以及基于属性的配置中创建" SessionFactory"。
对于基于属性的配置,我们可以有一个属性文件并在类中读取它,但为简单起见,我在类本身中创建Properties实例。
package com.theitroad.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.theitroad.hibernate.model.Employee1;
public class HibernateUtil {
//XML based configuration
private static SessionFactory sessionFactory;
//Annotation based configuration
private static SessionFactory sessionAnnotationFactory;
//Property based configuration
private static SessionFactory sessionJavaConfigFactory;
private static SessionFactory buildSessionFactory() {
try {
//Create the SessionFactory from hibernate.cfg.xml
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) {
//Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionAnnotationFactory() {
try {
//Create the SessionFactory from hibernate.cfg.xml
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) {
//Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
//Create Properties, can be read from property files too
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", "hyman");
props.put("hibernate.connection.password", "hyman123");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
//we can set mapping file or class with annotation
//addClass(Employee1.class) will look for resource
//com/theitroad/hibernate/model/Employee1.hbm.xml (not good)
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还是基于注释,为基于XML的配置创建`SessionFactory'都是相同的。
对于基于属性的属性,我们需要在"配置"对象中设置属性,并在创建"会话工厂"之前添加注释类。
整体创建SessionFactory包括以下步骤:
创建
Configuration对象并对其进行配置创建
ServiceRegistry对象并应用配置设置。通过传递ServiceRegistry对象作为参数来使用configuration.buildSessionFactory()以获取SessionFactory对象。
现在我们的应用程序几乎准备就绪,让我们编写一些测试程序并执行它们。
Hibernate XML配置测试
我们的测试程序如下所示。
package com.theitroad.hibernate.main;
import java.util.Date;
import org.hibernate.Session;
import com.theitroad.hibernate.model.Employee;
import com.theitroad.hibernate.util.HibernateUtil;
public class HibernateMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("hyman");
emp.setRole("CEO");
emp.setInsertTime(new Date());
//Get Session
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
System.out.println("Employee ID="+emp.getId());
//terminate session factory, otherwise program won't end
HibernateUtil.getSessionFactory().close();
}
}
该程序是自我理解的,当我们执行测试程序时,我们得到以下输出。
Jan 06, 2014 12:40:06 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jan 06, 2014 12:40:06 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Jan 06, 2014 12:40:06 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 06, 2014 12:40:06 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
Jan 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Jan 06, 2014 12:40:07 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: employee.hbm.xml
Jan 06, 2014 12:40:08 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Configuration loaded
Hibernate serviceRegistry created
Jan 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!)
Jan 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]
Jan 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=hyman, password=}
Jan 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jan 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Jan 06, 2014 12:40:08 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jan 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
Jan 06, 2014 12:40:08 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jan 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
Jan 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.theitroad.hibernate.main;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.theitroad.hibernate.model.Employee1;
import com.theitroad.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());
//Get Session
SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
Session session = sessionFactory.getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
System.out.println("Employee ID="+emp.getId());
//terminate session factory, otherwise program won't end
sessionFactory.close();
}
}
当我们执行上面的程序时,我们得到以下输出。
Jan 06, 2014 12:42:22 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jan 06, 2014 12:42:22 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Jan 06, 2014 12:42:22 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 06, 2014 12:42:22 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate-annotation.cfg.xml
Jan 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate-annotation.cfg.xml
Jan 06, 2014 12:42:23 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Annotation Configuration loaded
Hibernate Annotation serviceRegistry created
Jan 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!)
Jan 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]
Jan 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=hyman, password=}
Jan 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jan 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 06, 2014 12:42:23 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Jan 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
Jan 06, 2014 12:42:23 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jan 06, 2014 12:42:23 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee ID=20
Jan 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.theitroad.hibernate.main;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.theitroad.hibernate.model.Employee1;
import com.theitroad.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());
//Get Session
SessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();
Session session = sessionFactory.getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
System.out.println("Employee ID="+emp.getId());
//terminate session factory, otherwise program won't end
sessionFactory.close();
}
}
以上测试程序的输出为:
Jan 06, 2014 12:45:09 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jan 06, 2014 12:45:09 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Jan 06, 2014 12:45:09 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 06, 2014 12:45:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Hibernate Java Config serviceRegistry created
Jan 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!)
Jan 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]
Jan 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=hyman, password=}
Jan 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jan 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 06, 2014 12:45:10 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Jan 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
Jan 06, 2014 12:45:10 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jan 06, 2014 12:45:10 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee ID=21
Jan 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

