欢迎来到Hibernate初学者教程。Hibernate 是使用最广泛的** Java ORM** 工具。大多数应用程序使用关系数据库来存储应用程序信息,在低级别,我们使用[JDBC API](/community/tutorials/jdbc-tutorial)连接到数据库并执行CRUD操作。
初学者休眠教程
如果你看一下JDBC代码,就会发现有太多的样板代码,而且有可能出现资源泄漏和数据不一致,因为所有的工作都需要由开发人员完成。这就是ORM工具派上用场的地方。对象关系映射 或 ** ORM** 是将应用程序域模型对象映射到关系数据库表的编程技术。Hibernate是一个基于Java的ORM工具,它提供了将应用程序域对象映射到关系数据库表的框架,反之亦然。使用Hibernate作为ORM工具的一些好处是:
1.支持Java类到数据库表的映射,反之亦然。它提供了跨所有主要关系数据库执行CRUD操作的功能。 2.Hibernate消除了JDBC附带的所有样板代码,并负责管理资源,因此我们可以专注于业务用例,而不是确保数据库操作不会导致资源泄漏。 3.Hibernate支持事务管理,确保系统中不存在不一致的数据。 4.由于我们使用XML、属性文件或注释来将Java类映射到数据库表,因此它在应用程序和数据库之间提供了抽象层。 5.Hibernate帮助我们映射连接、集合、继承对象,并且我们可以很容易地可视化我们的模型类如何表示数据库表。 6.Hibernate提供了一种类似于SQL的强大查询语言(HQL)。然而,HQL是完全面向对象的,并且理解继承、多态和关联等概念。 7.Hibernate还提供与一些外部模块的集成。例如,Hibernate Validator是Bean验证的参考实现(JSR303)。 8.Hibernate是红帽社区的开源项目,在全球范围内使用。这使它成为一个比其他更好的选择,因为学习曲线很小,有大量的在线文档和帮助,很容易在论坛上找到。 9.Hibernate很容易与其他Java EE框架集成,非常受欢迎,以至于[SpringJDBBC和JdbcTemplate CRUD with DataSource示例教程》)提供了内置的对Hibernate与Framework](/community/tutorials/spring-jdbc-example应用程序集成的支持。
我希望以上所有的好处能让您相信Hibernate是满足应用程序对象关系映射需求的最佳选择。现在让我们来看看Hibernate框架的架构,然后我们将进入示例项目,在那里我们将研究在独立的Java应用程序中配置Hibernate并使用它的不同方法。
Hibernate架构
下图显示了Hibernate架构,以及它如何作为应用程序类和用于数据库操作的JDBC/JTA API之间的抽象层工作。很明显,Hibernate构建在JDBC和JTA API之上。的Hibernate教程让我们逐一了解Hibernate架构的核心组件。
- SessionFactory(org.hibernate.SessionFactory) :SessionFactory是单个数据库的已编译映射的不可变的线程安全缓存。我们可以使用
SessionFactory
获取org.hibernate.Session
的实例。 - Session(org.hibernate.Session) :Session是一个单线程的短暂对象,表示应用程序和持久化存储之间的对话。它包装了JDBC
java.sql.Connection
,并作为org.hibernate.Transaction
的工厂。 - 持久化对象 :持久化对象是短暂的单线程对象,包含持久化状态和业务功能。这些可以是普通的JavaBean/POJO。它们正好与一个
org.hibernate.Session
相关联。 - 暂态对象 :暂态对象是当前未关联
org.hibernate.Session
的持久化类实例。它们可能已被应用程序实例化但尚未持久化,或者它们可能已被关闭的org.hibernate.Session
实例化。 - Transaction(org.hibernate.Transaction) :Transaction是应用程序用来指定原子工作单元的单线程、短暂对象。它从底层的JDBC或JTA事务中抽象出应用程序。在某些情况下,一个
org.hibernate.Session
可能会跨越多个org.hibernate.Transaction
。 - ConnectionProvider JDBC ConnectionProvider是(org.hibernate.connection.ConnectionProvider) :连接的工厂。它提供了应用程序与底层
javax.sql.DataSource
或java.sql.DriverManager
之间的抽象。它不向应用程序公开,但可以由开发人员扩展。 - TransactionFactory(org.hibernate.TransactionFactory) :
org.hibernate.Transaction
实例的工厂。
Hibernate与Java持久化API(JPA)
Hibernate提供了Java持久化API 的实现,所以我们可以将JPA注释与模型Bean一起使用,Hibernate会负责将其配置为用于CRUD操作。我们将通过注解示例来研究这一点。
休眠示例
在开发Hibernate应用程序时,我们需要提供两组配置。第一组配置包含将用于创建数据库连接和会话对象的数据库特定属性。第二组配置包含模型类和数据库表之间的映射。对于数据库连接相关的配置,我们可以使用基于XML或基于属性的配置。我们可以使用基于XML或基于注释的配置来提供模型类和数据库表映射。我们将使用来自javax.persistence
的JPA注释进行基于注释的映射。我们的最终项目将看起来像下面的图像。在Eclipse或您喜欢的IDE中创建Maven项目,您可以保留任何您选择的名称。在我们继续项目的不同组件之前,我们必须进行数据库设置。
数据库表设置
在我的例子中,我使用的是MySQL数据库,下面的脚本用来创建所需的表。
1CREATE TABLE `Employee` (
2 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
3 `name` varchar(20) DEFAULT NULL,
4 `role` varchar(20) DEFAULT NULL,
5 `insert_time` datetime DEFAULT NULL,
6 PRIMARY KEY (`id`)
7) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
注意,Employee表的id
列是由MySQL自动生成的,因此我们不需要插入它。
Hibernate项目依赖
我们最终的pom.xml文件如下所示。
1<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">
2 <modelVersion>4.0.0</modelVersion>
3 <groupId>com.journaldev.hibernate</groupId>
4 <artifactId>HibernateExample</artifactId>
5 <version>0.0.1-SNAPSHOT</version>
6 <name>HibernateExample</name>
7
8 <dependencies>
9 <dependency>
10 <groupId>org.hibernate</groupId>
11 <artifactId>hibernate-core</artifactId>
12 <version>4.3.5.Final</version>
13 </dependency>
14 <!-- Hibernate 4 uses Jboss logging, but older versions slf4j for logging -->
15 <dependency>
16 <groupId>org.slf4j</groupId>
17 <artifactId>slf4j-simple</artifactId>
18 <version>1.7.5</version>
19 </dependency>
20 <dependency>
21 <groupId>mysql</groupId>
22 <artifactId>mysql-connector-java</artifactId>
23 <version>5.0.5</version>
24 </dependency>
25 </dependencies>
26
27 <build>
28 <finalName>${project.artifactId}</finalName>
29 </build>
30</project>
Hibernate-core Artiture包含了所有核心Hibernate类,因此我们将通过将其包含在项目中来获取所有必要的功能。请注意,我在样例项目中使用的是最新的Hibernate版本(4.3.5 Final),而Hibernate仍在发展中,我已经看到许多核心类在每个主要版本之间都会发生变化。因此,如果您使用的是任何其他版本,那么您必须修改Hibernate配置才能使其工作的可能性很小。不过,我确信它在所有4.x.x版本中都能正常工作。Hibernate4使用JBoss日志记录,但旧版本使用slf4j进行日志记录,所以我在我的项目中包含了** slf4j-Simple** 构件,虽然不需要,因为我使用的是Hibernate4。** mySQL-Connector-Java** 是用于连接到MySQL数据库的MySQL驱动程序,如果您正在使用任何其他数据库,则添加相应的驱动程序构件。
域名模型类
正如你在上面的图片中看到的,我们有两个模型类,Employee
和Please 1
。Employee是一个简单的Java Bean类,我们将使用基于XML的配置来提供它的映射细节。Java1是一个javabean,其中的字段使用JPA注释进行注释,因此我们不需要在单独的XML文件中提供映射。
1package com.journaldev.hibernate.model;
2
3import java.util.Date;
4
5public class Employee {
6
7 private int id;
8 private String name;
9 private String role;
10 private Date insertTime;
11
12 public int getId() {
13 return id;
14 }
15 public void setId(int id) {
16 this.id = id;
17 }
18 public String getName() {
19 return name;
20 }
21 public void setName(String name) {
22 this.name = name;
23 }
24 public String getRole() {
25 return role;
26 }
27 public void setRole(String role) {
28 this.role = role;
29 }
30 public Date getInsertTime() {
31 return insertTime;
32 }
33 public void setInsertTime(Date insertTime) {
34 this.insertTime = insertTime;
35 }
36
37}
Employee类是简单的Java Bean,这里没有什么特别要讨论的。
1package com.journaldev.hibernate.model;
2
3import java.util.Date;
4
5import javax.persistence.Column;
6import javax.persistence.Entity;
7import javax.persistence.GeneratedValue;
8import javax.persistence.GenerationType;
9import javax.persistence.Id;
10import javax.persistence.Table;
11import javax.persistence.UniqueConstraint;
12
13@Entity
14@Table(name="Employee",
15 uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
16public class Employee1 {
17
18 @Id
19 @GeneratedValue(strategy=GenerationType.IDENTITY)
20 @Column(name="ID", nullable=false, unique=true, length=11)
21 private int id;
22
23 @Column(name="NAME", length=20, nullable=true)
24 private String name;
25
26 @Column(name="ROLE", length=20, nullable=true)
27 private String role;
28
29 @Column(name="insert_time", nullable=true)
30 private Date insertTime;
31
32 public int getId() {
33 return id;
34 }
35 public void setId(int id) {
36 this.id = id;
37 }
38 public String getName() {
39 return name;
40 }
41 public void setName(String name) {
42 this.name = name;
43 }
44 public String getRole() {
45 return role;
46 }
47 public void setRole(String role) {
48 this.role = role;
49 }
50 public Date getInsertTime() {
51 return insertTime;
52 }
53 public void setInsertTime(Date insertTime) {
54 this.insertTime = insertTime;
55 }
56}
由于Hibernate提供了JPA实现,所以使用javax.sistence.Entity
注释将一个类标记为实体Bean,可以由Hibernate持久化。javax.sistence.Table
注释用于定义列的表映射和唯一约束。javax.sistence.Id
注释用于定义表的主键。javax.sistence.GeneratedValue
用于定义自动生成字段,并使用GenerationType.IDENTITY 策略,将生成的id值映射到Bean,并在Java程序中检索。javax.sistence.Column
用于将字段映射到表列,我们还可以为Bean属性指定长度、可空和唯一性。
Hibernate映射XML配置
如上所述,我们将使用基于XML的配置进行Employee类映射。我们可以选择任何名称,但为了清楚起见,最好选择表名或Java Bean名。我们的Employee Bean的Hibernate映射文件如下所示。ployee.hbm.xml
1<?xml version="1.0"?>
2<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
4
5<hibernate-mapping>
6 <class name="com.journaldev.hibernate.model.Employee" table="EMPLOYEE">
7 <id name="id" type="int">
8 <column name="ID" />
9 <generator class="increment" />
10 </id>
11 <property name="name" type="java.lang.String">
12 <column name="NAME" />
13 </property>
14 <property name="role" type="java.lang.String">
15 <column name="ROLE" />
16 </property>
17 <property name="insertTime" type="timestamp">
18 <column name="insert_time" />
19 </property>
20 </class>
21</hibernate-mapping>
XML配置很简单,其功能与基于注释的配置相同。
Hibernate配置文件
我们将创建两个Hibernate配置XML文件--一个用于基于XML的配置,另一个用于基于注释的配置。hibernate.cfg.xml
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5<hibernate-configuration>
6 <session-factory>
7 <!-- Database connection properties - Driver, URL, user, password -->
8 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
9 <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
10 <property name="hibernate.connection.username">pankaj</property>
11 <property name="hibernate.connection.password">pankaj123</property>
12 <!-- Connection Pool Size -->
13 <property name="hibernate.connection.pool_size">1</property>
14
15 <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
16 <property name="hibernate.current_session_context_class">thread</property>
17
18 <!-- Outputs the SQL queries, should be disabled in Production -->
19 <property name="hibernate.show_sql">true</property>
20
21 <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
22 Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
23 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
24
25 <!-- mapping file, we can use Bean annotations too -->
26 <mapping resource="employee.hbm.xml" />
27 </session-factory>
28</hibernate-configuration>
大多数属性与数据库配置有关,其他属性的详细信息在注释中给出。注意Hibernate映射文件的配置,我们可以在这里定义多个Hibernate映射文件并进行配置。还要注意,映射是特定于会话工厂的。hibernate-nottation.cfg.xml
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5<hibernate-configuration>
6 <session-factory>
7 <!-- Database connection properties - Driver, URL, user, password -->
8 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
9 <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
10 <property name="hibernate.connection.username">pankaj</property>
11 <property name="hibernate.connection.password">pankaj123</property>
12
13 <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
14 <property name="hibernate.current_session_context_class">thread</property>
15
16 <!-- Mapping with model class containing annotations -->
17 <mapping class="com.journaldev.hibernate.model.Employee1"/>
18 </session-factory>
19</hibernate-configuration>
大部分配置与基于XML的配置相同,唯一不同的是映射配置。我们可以为类和包提供映射配置。
休眠SessionFactory
我已经创建了一个实用程序类,我从基于XML的配置以及基于属性的配置创建SessionFactory
。对于基于属性的配置,我们可以有一个属性文件并在类中读取它,但为了简单起见,我在类本身中创建Properties实例。
1package com.journaldev.hibernate.util;
2
3import java.util.Properties;
4
5import org.hibernate.SessionFactory;
6import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
7import org.hibernate.cfg.Configuration;
8import org.hibernate.service.ServiceRegistry;
9
10import com.journaldev.hibernate.model.Employee1;
11
12public class HibernateUtil {
13
14 //XML based configuration
15 private static SessionFactory sessionFactory;
16
17 //Annotation based configuration
18 private static SessionFactory sessionAnnotationFactory;
19
20 //Property based configuration
21 private static SessionFactory sessionJavaConfigFactory;
22
23 private static SessionFactory buildSessionFactory() {
24 try {
25 // Create the SessionFactory from hibernate.cfg.xml
26 Configuration configuration = new Configuration();
27 configuration.configure("hibernate.cfg.xml");
28 System.out.println("Hibernate Configuration loaded");
29
30 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
31 System.out.println("Hibernate serviceRegistry created");
32
33 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
34
35 return sessionFactory;
36 }
37 catch (Throwable ex) {
38 // Make sure you log the exception, as it might be swallowed
39 System.err.println("Initial SessionFactory creation failed." + ex);
40 throw new ExceptionInInitializerError(ex);
41 }
42 }
43
44 private static SessionFactory buildSessionAnnotationFactory() {
45 try {
46 // Create the SessionFactory from hibernate.cfg.xml
47 Configuration configuration = new Configuration();
48 configuration.configure("hibernate-annotation.cfg.xml");
49 System.out.println("Hibernate Annotation Configuration loaded");
50
51 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
52 System.out.println("Hibernate Annotation serviceRegistry created");
53
54 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
55
56 return sessionFactory;
57 }
58 catch (Throwable ex) {
59 // Make sure you log the exception, as it might be swallowed
60 System.err.println("Initial SessionFactory creation failed." + ex);
61 throw new ExceptionInInitializerError(ex);
62 }
63 }
64
65 private static SessionFactory buildSessionJavaConfigFactory() {
66 try {
67 Configuration configuration = new Configuration();
68
69 //Create Properties, can be read from property files too
70 Properties props = new Properties();
71 props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
72 props.put("hibernate.connection.url", "jdbc:mysql://localhost/TestDB");
73 props.put("hibernate.connection.username", "pankaj");
74 props.put("hibernate.connection.password", "pankaj123");
75 props.put("hibernate.current_session_context_class", "thread");
76
77 configuration.setProperties(props);
78
79 //we can set mapping file or class with annotation
80 //addClass(Employee1.class) will look for resource
81 // com/journaldev/hibernate/model/Employee1.hbm.xml (not good)
82 configuration.addAnnotatedClass(Employee1.class);
83
84 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
85 System.out.println("Hibernate Java Config serviceRegistry created");
86
87 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
88
89 return sessionFactory;
90 }
91 catch (Throwable ex) {
92 System.err.println("Initial SessionFactory creation failed." + ex);
93 throw new ExceptionInInitializerError(ex);
94 }
95 }
96
97 public static SessionFactory getSessionFactory() {
98 if(sessionFactory == null) sessionFactory = buildSessionFactory();
99 return sessionFactory;
100 }
101
102 public static SessionFactory getSessionAnnotationFactory() {
103 if(sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
104 return sessionAnnotationFactory;
105 }
106
107 public static SessionFactory getSessionJavaConfigFactory() {
108 if(sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
109 return sessionJavaConfigFactory;
110 }
111
112}
无论映射是基于XML还是基于注释,为基于XML的配置创建SessionFactory
都是相同的。对于基于属性的,我们需要在Configuration
对象中设置属性,并在创建SessionFactory
之前添加注释类。创建SessionFactory总体包括以下步骤:
1.创建Configuration
对象并进行配置
2.创建ServiceRegistry
对象并应用配置设置。
3.通过传入ServiceRegistry
对象作为参数,使用Configuration.BuildSessionFactory()
获取SessionFactory
对象。
我们的应用程序现在差不多准备好了,让我们编写一些测试程序并执行它们。
Hibernate XML配置测试
我们的测试程序如下所示。
1package com.journaldev.hibernate.main;
2
3import java.util.Date;
4
5import org.hibernate.Session;
6
7import com.journaldev.hibernate.model.Employee;
8import com.journaldev.hibernate.util.HibernateUtil;
9
10public class HibernateMain {
11
12 public static void main(String[] args) {
13 Employee emp = new Employee();
14 emp.setName("Pankaj");
15 emp.setRole("CEO");
16 emp.setInsertTime(new Date());
17
18 //Get Session
19 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
20 //start transaction
21 session.beginTransaction();
22 //Save the Model object
23 session.save(emp);
24 //Commit transaction
25 session.getTransaction().commit();
26 System.out.println("Employee ID="+emp.getId());
27
28 //terminate session factory, otherwise program won't end
29 HibernateUtil.getSessionFactory().close();
30 }
31
32}
该程序是自理解的,当我们执行测试程序时,我们得到以下输出。
1May 06, 2014 12:40:06 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
2INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
3May 06, 2014 12:40:06 AM org.hibernate.Version logVersion
4INFO: HHH000412: Hibernate Core {4.3.5.Final}
5May 06, 2014 12:40:06 AM org.hibernate.cfg.Environment <clinit>
6INFO: HHH000206: hibernate.properties not found
7May 06, 2014 12:40:06 AM org.hibernate.cfg.Environment buildBytecodeProvider
8INFO: HHH000021: Bytecode provider name : javassist
9May 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration configure
10INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
11May 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration getConfigurationInputStream
12INFO: HHH000040: Configuration resource: hibernate.cfg.xml
13May 06, 2014 12:40:07 AM org.hibernate.cfg.Configuration addResource
14INFO: HHH000221: Reading mappings from resource: employee.hbm.xml
15May 06, 2014 12:40:08 AM org.hibernate.cfg.Configuration doConfigure
16INFO: HHH000041: Configured SessionFactory: null
17Hibernate Configuration loaded
18Hibernate serviceRegistry created
19May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
20WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
21May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
22INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
23May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
24INFO: HHH000046: Connection properties: {user=pankaj, password=****}
25May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
26INFO: HHH000006: Autocommit mode: false
27May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
28INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
29May 06, 2014 12:40:08 AM org.hibernate.dialect.Dialect <init>
30INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
31May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
32INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
33May 06, 2014 12:40:08 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
34INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
35May 06, 2014 12:40:08 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
36INFO: HHH000397: Using ASTQueryTranslatorFactory
37Hibernate: select max(ID) from EMPLOYEE
38Hibernate: insert into EMPLOYEE (NAME, ROLE, insert_time, ID) values (?, ?, ?, ?)
39Employee ID=19
40May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
41INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]
请注意,它正在打印生成的员工ID,您可以检查数据库表以确认它。
Hibernate注释配置测试
1package com.journaldev.hibernate.main;
2
3import java.util.Date;
4
5import org.hibernate.Session;
6import org.hibernate.SessionFactory;
7
8import com.journaldev.hibernate.model.Employee1;
9import com.journaldev.hibernate.util.HibernateUtil;
10
11public class HibernateAnnotationMain {
12
13 public static void main(String[] args) {
14 Employee1 emp = new Employee1();
15 emp.setName("David");
16 emp.setRole("Developer");
17 emp.setInsertTime(new Date());
18
19 //Get Session
20 SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
21 Session session = sessionFactory.getCurrentSession();
22 //start transaction
23 session.beginTransaction();
24 //Save the Model object
25 session.save(emp);
26 //Commit transaction
27 session.getTransaction().commit();
28 System.out.println("Employee ID="+emp.getId());
29
30 //terminate session factory, otherwise program won't end
31 sessionFactory.close();
32 }
33
34}
当我们执行上面的程序时,我们得到以下输出。
1May 06, 2014 12:42:22 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
2INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
3May 06, 2014 12:42:22 AM org.hibernate.Version logVersion
4INFO: HHH000412: Hibernate Core {4.3.5.Final}
5May 06, 2014 12:42:22 AM org.hibernate.cfg.Environment <clinit>
6INFO: HHH000206: hibernate.properties not found
7May 06, 2014 12:42:22 AM org.hibernate.cfg.Environment buildBytecodeProvider
8INFO: HHH000021: Bytecode provider name : javassist
9May 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration configure
10INFO: HHH000043: Configuring from resource: hibernate-annotation.cfg.xml
11May 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration getConfigurationInputStream
12INFO: HHH000040: Configuration resource: hibernate-annotation.cfg.xml
13May 06, 2014 12:42:23 AM org.hibernate.cfg.Configuration doConfigure
14INFO: HHH000041: Configured SessionFactory: null
15Hibernate Annotation Configuration loaded
16Hibernate Annotation serviceRegistry created
17May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
18WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
19May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
20INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
21May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
22INFO: HHH000046: Connection properties: {user=pankaj, password=****}
23May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
24INFO: HHH000006: Autocommit mode: false
25May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
26INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
27May 06, 2014 12:42:23 AM org.hibernate.dialect.Dialect <init>
28INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
29May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
30INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
31May 06, 2014 12:42:23 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
32INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
33May 06, 2014 12:42:23 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
34INFO: HHH000397: Using ASTQueryTranslatorFactory
35Employee ID=20
36May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
37INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]
查看输出并将其与基于XML的配置的输出进行比较,您会注意到一些不同之处。例如,我们没有为基于注释的配置设置连接池大小,因此将其设置为缺省值20。
Hibernate Java配置测试
1package com.journaldev.hibernate.main;
2
3import java.util.Date;
4
5import org.hibernate.Session;
6import org.hibernate.SessionFactory;
7
8import com.journaldev.hibernate.model.Employee1;
9import com.journaldev.hibernate.util.HibernateUtil;
10
11public class HibernateJavaConfigMain {
12
13 public static void main(String[] args) {
14 Employee1 emp = new Employee1();
15 emp.setName("Lisa");
16 emp.setRole("Manager");
17 emp.setInsertTime(new Date());
18
19 //Get Session
20 SessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();
21 Session session = sessionFactory.getCurrentSession();
22 //start transaction
23 session.beginTransaction();
24 //Save the Model object
25 session.save(emp);
26 //Commit transaction
27 session.getTransaction().commit();
28 System.out.println("Employee ID="+emp.getId());
29
30 //terminate session factory, otherwise program won't end
31 sessionFactory.close();
32 }
33
34}
上述测试程序的输出为:
1May 06, 2014 12:45:09 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
2INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
3May 06, 2014 12:45:09 AM org.hibernate.Version logVersion
4INFO: HHH000412: Hibernate Core {4.3.5.Final}
5May 06, 2014 12:45:09 AM org.hibernate.cfg.Environment <clinit>
6INFO: HHH000206: hibernate.properties not found
7May 06, 2014 12:45:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
8INFO: HHH000021: Bytecode provider name : javassist
9Hibernate Java Config serviceRegistry created
10May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
11WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
12May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
13INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
14May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
15INFO: HHH000046: Connection properties: {user=pankaj, password=****}
16May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
17INFO: HHH000006: Autocommit mode: false
18May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
19INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
20May 06, 2014 12:45:10 AM org.hibernate.dialect.Dialect <init>
21INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
22May 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
23INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
24May 06, 2014 12:45:10 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
25INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
26May 06, 2014 12:45:10 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
27INFO: HHH000397: Using ASTQueryTranslatorFactory
28Employee ID=21
29May 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
30INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]
这就是面向初学者的Hibernate教程,我希望它足以让您入门。在以后的教程中,我们将研究Hibernate框架的不同特性。从下面的链接下载完整的项目,并使用它了解更多信息。