初学者 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 Validation (JSR 303) 的参考实现。
- Hibernate 是 Red Hat 社区的一个开源项目,在全球范围内使用。这使得它成为比其他项目更好的选择,因为学习难度低,有大量在线文档,论坛上很容易获得帮助。
- Hibernate 很容易与其他 Java EE 框架集成,它非常流行,以至于Spring Framework提供了内置支持将 Hibernate 与 Spring 应用程序集成。
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 Architecture
Below image shows the Hibernate architecture and how it works as an abstraction layer between application classes and JDBC/JTA APIs for database operations. It’s clear that Hibernate is built on top of JDBC and JTA APIs. Let’s look at the core components of hibernate architecture one by one.
- SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We can get instance of
org.hibernate.Session
usingSessionFactory
. - Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC
java.sql.Connection
and works as a factory fororg.hibernate.Transaction
. - Persistent objects: Persistent objects are short-lived, single threaded objects that contains persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one
org.hibernate.Session
. - Transient objects: Transient objects are persistent classes instances that are not currently associated with a
org.hibernate.Session
. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closedorg.hibernate.Session
. - Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A
org.hibernate.Session
might span multipleorg.hibernate.Transaction
in some cases. - ConnectionProvider (org.hibernate.connection.ConnectionProvider): ConnectionProvider is a factory for JDBC connections. It provides abstraction between the application and underlying
javax.sql.DataSource
orjava.sql.DriverManager
. It is not exposed to application, but it can be extended by the developer. - TransactionFactory (org.hibernate.TransactionFactory): A factory for
org.hibernate.Transaction
instances.
Hibernate and Java Persistence API (JPA)
Hibernate provides implementation of Java Persistence API, so we can use JPA annotations with model beans and hibernate will take care of configuring it to be used in CRUD operations. We will look into this with annotations example.
Hibernate Example
When developing hibernate applications, we need to provide two set of configuration. First set of configuration contains database specific properties that will be used to create Database connection and Session objects. Second set of configurations contains mapping between model classes and database tables. We can use XML based or properties based configuration for database connection related configurations. We can use XML based or annotation based configurations for providing model classes and database tables mapping. We will use JPA annotations from javax.persistence
for annotation based mappings. Our final project will look like below image. Create a Maven project in Eclipse or your favorite IDE, you can keep any name of your choice. Before we move on to the different components of the project, we will have to do the database setup.
Database Table Setup
For my example, I am using MySQL database and below script is used to create necessary table.
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;
Notice that Employee table “id” column is automatically generated by MySQL, so we don’t need to insert it.
Hibernate Project Dependencies
Our final pom.xml file looks like below.
<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 artifact contains all the core hibernate classes, so we will get all the necessary features by including it in the project. Note that I am using latest Hibernate version (4.3.5.Final) for my sample project and Hibernate is still evolving and I have seen that a lot of core classes change between every major release. So if you are using any other version, there is a small chance that you will have to modify the Hibernate configurations for it to work. However, I am sure that it will work fine for all the 4.x.x releases. Hibernate 4 uses JBoss logging but older versions uses slf4j for logging purposes, so I have included slf4j-simple artifact in my project, although not needed because I am using Hibernate 4. mysql-connector-java is the MySQL driver for connecting to MySQL databases, if you are using any other database then add corresponding driver artifact.
Domain Model Classes
As you can see in above image that we have two model classes, Employee
and Employee1
. Employee is a simple Java Bean class and we will use XML based configuration for providing it’s mapping details. Employee1 is a java bean where fields are annotated with JPA annotations, so that we don’t need to provide mapping in separate XML file.
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 class is simple java bean, there is nothing specific to discuss here.
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
annotation is used to mark a class as Entity bean that can be persisted by hibernate, since hibernate provides JPA implementation. javax.persistence.Table
annotation is used to define the table mapping and unique constraints for the columns. javax.persistence.Id
annotation is used to define the primary key for the table. javax.persistence.GeneratedValue
is used to define that the field will be auto generated and GenerationType.IDENTITY strategy is used so that the generated “id” value is mapped to the bean and can be retrieved in the java program. javax.persistence.Column
is used to map the field with table column, we can also specify length, nullable and uniqueness for the bean properties.
Hibernate Mapping XML Configuration
As stated above, we will use XML based configuration for Employee class mapping. We can choose any name, but it’s good to choose with table or java bean name for clarity. Our hibernate mapping file for Employee bean looks like below. 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>
The xml configuration is simple and does the same thing as annotation based configuration.
Hibernate Configuration Files
We will create two hibernate configuration xml files - one for xml based configuration and another for annotation based configuration. 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>
Most of the properties are related to database configurations, other properties details are given in comment. Note the configuration for hibernate mapping file, we can define multiple hibernate mapping files and configure them here. Also note that mapping is specific to session factory. 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>
Most of the configuration is same as XML based configuration, the only difference is the mapping configuration. We can provide mapping configuration for classes as well as packages.
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 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", "pankaj");
props.put("hibernate.connection.password", "pankaj123");
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/journaldev/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;
}
}
Creating SessionFactory
for XML based configuration is same whether mapping is XML based or annotation based. For properties based, we need to set the properties in Configuration
object and add annotation classes before creating the SessionFactory
. Overall creating SessionFactory includes following steps:
- Creating
Configuration
object and configure it - Creating
ServiceRegistry
object and apply configuration settings. - Use
configuration.buildSessionFactory()
by passingServiceRegistry
object as argument to get theSessionFactory
object.
Our application is almost ready now, let’s write some test programs and execute them.
Hibernate XML Configuration Test
Our test program looks like below.
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());
//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();
}
}
The program is self understood, when we execute the test program, we get following output.
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]
Notice that it’s printing the generated employee id, you can check database table to confirm it.
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());
//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();
}
}
当我们执行上述程序时,我们得到以下输出。
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());
//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();
}
}
上述测试程序的输出为:
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 初学者项目