matlab初学者教程

Welcome to the Hibernate tutorial for Beginners. Hibernate is one of the most widely used Java ORM tool. Most of the applications use relational databases to store application information and at the low level we use JDBC API for connecting to databases and perform CRUD operations.

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

初学者Hibernate指南 (Hibernate Tutorial for Beginners)

If you look at the JDBC code, there is so much of boiler plate code and there are chances of resource leak and data inconsistency because all the work needs to be done by the developer. This is where an ORM tool comes handy.

如果您查看JDBC代码,那么会有很多样板代码,并且有资源泄漏和数据不一致的可能性,因为所有工作都需要开发人员来完成。 这是ORM工具派上用场的地方。

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.

对象关系映射对象关系管理ORM)是将应用程序域模型对象映射到关系数据库表的编程技术。 Hibernate是基于Java的ORM工具,它提供了用于将应用程序域对象映射到关系数据库表,反之亦然的框架。

Some of the benefits of using Hibernate as ORM tool are:

使用Hibernate作为ORM工具的一些好处是:

  1. Hibernate supports mapping of java classes to database tables and vice versa. It provides features to perform CRUD operations across all the major relational databases.Hibernate支持将Java类映射到数据库表,反之亦然。 它提供了跨所有主要关系数据库执行CRUD操作的功能。
  2. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business use cases rather than making sure that database operations are not causing resource leaks.Hibernate消除了JDBC附带的所有样板代码,并负责管理资源,因此我们可以专注于业务用例,而不是确保数据库操作不会引起资源泄漏。
  3. Hibernate supports transaction management and make sure there is no inconsistent data present in the system.Hibernate支持事务管理,并确保系统中没有不一致的数据。
  4. Since we use XML, property files or annotations for mapping java classes to database tables, it provides an abstraction layer between application and database.由于我们使用XML,属性文件或批注将Java类映射到数据库表,因此它提供了应用程序和数据库之间的抽象层。
  5. Hibernate helps us in mapping joins, collections, inheritance objects and we can easily visualize how our model classes are representing database tables.Hibernate帮助我们映射联接,集合,继承对象,并且我们可以轻松地可视化模型类如何表示数据库表。
  6. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.Hibernate提供了一种与SQL类似的强大查询语言(HQL)。 但是,HQL完全面向对象,并且了解诸如继承,多态性和关联之类的概念。
  7. Hibernate also offers integration with some external modules. For example Hibernate Validator is the reference implementation of Bean Validation (JSR 303).Hibernate还提供了与某些外部模块的集成。 例如,Hibernate Validator是Bean验证(JSR 303)的参考实现。
  8. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.Hibernate是Red Hat Community的一个开源项目,已在全球范围内使用。 这使它成为比其他方法更好的选择,因为学习曲线很小,并且有大量的在线文档,并且可以在论坛中轻松获得帮助。
  9. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.Hibernate易于与其他Java EE框架集成,因此非常流行, Spring框架提供了将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是满足应用程序对象关系映射要求的最佳选择。 现在让我们看一下Hibernate Framework架构,然后我们将跳至示例项目,在此我们将探讨在独立的Java应用程序中配置Hibernate并使用它的不同方法。

Hibernate架构 (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.

下图显示了Hibernate体系结构以及它如何充当应用程序类和JDBC / JTA API之间的抽象层以进行数据库操作。 显然,Hibernate是建立在JDBC和JTA API之上的。

Let’s look at the core components of hibernate architecture one by one.

让我们一一介绍一下Hibernate架构的核心组件。

  • 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 using SessionFactory.SessionFactory(org.hibernate.SessionFactory) :SessionFactory是单个数据库的已编译映射的不可变线程安全缓存。 我们可以使用SessionFactory获得org.hibernate.Session实例。
  • 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 for org.hibernate.Transaction.会话(org.hibernate.Session) :会话是一个单线程的,短暂的对象,表示应用程序与持久性存储之间的对话。 它包装JDBC java.sql.Connection并用作org.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.持久对象 :持久对象是包含持久状态和业务功能的短寿命单线程对象。 这些可以是普通的JavaBeans / POJO。 它们仅与一个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 closed org.hibernate.Session.临时对象 :临时对象是当前未与org.hibernate.Session关联的持久类实例。 它们可能已被应用程序实例化但尚未持久化,或者它们可能已被封闭的org.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 multiple org.hibernate.Transaction in some cases.事务(org.hibernate.Transaction) :事务是应用程序用来指定原子工作单元的单线程,短期对象。 它将应用程序从底层的JDBC或JTA事务中抽象出来。 在某些情况下,一个org.hibernate.Session可能跨越多个org.hibernate.Transaction
  • ConnectionProvider (org.hibernate.connection.ConnectionProvider): ConnectionProvider is a factory for JDBC connections. It provides abstraction between the application and underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended by the developer.ConnectionProvider(org.hibernate.connection.ConnectionProvider) :ConnectionProvider是JDBC连接的工厂。 它提供了应用程序与基础javax.sql.DataSourcejava.sql.DriverManager之间的抽象。 它没有公开给应用程序,但是可以由开发人员扩展。
  • TransactionFactory (org.hibernate.TransactionFactory): A factory for org.hibernate.Transaction instances.TransactionFactory(org.hibernate.TransactionFactory)org.hibernate.Transaction实例的工厂。

Hibernate和Java Persistence API(JPA) (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提供了Java Persistence API的实现 ,因此我们可以将JPA注释与模型bean一起使用,并且hibernate将负责配置它以便在CRUD操作中使用。 我们将通过注释示例对此进行研究。

Hibernate示例 (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.

在开发Hibernate应用程序时,我们需要提供两组配置。 第一组配置包含特定于数据库的属性,这些属性将用于创建数据库连接和会话对象。 第二组配置包含模型类和数据库表之间的映射。

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.

我们可以将基于XML或基于属性的配置用于与数据库连接相关的配置。 我们可以使用基于XML或基于注释的配置来提供模型类和数据库表映射。 我们将使用javax.persistence JPA批注进行基于批注的映射。

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.

在Eclipse或您最喜欢的IDE中创建一个Maven项目,您可以保留您选择的任何名称。 在继续进行项目的不同组件之前,我们将必须进行数据库设置。

数据库表设置 (Database Table Setup)

For my example, I am using MySQL database and below script is used to create necessary table.

对于我的示例,我使用的是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;

Notice that Employee table “id” column is automatically generated by MySQL, so we don’t need to insert it.

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

Hibernate项目依赖项 (Hibernate Project Dependencies)

Our final pom.xml file looks like below.

我们最终的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 artifact contains all the core hibernate classes, so we will get all the necessary features by including it in the project.

hibernate-core工件包含所有核心的hibernate类,因此我们将其包含在项目中来获得所有必需的功能。

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.3.5.Final),并且Hibernate仍在不断发展,并且我发现在每个主要发行版之间都有许多核心类会发生变化。 因此,如果您使用任何其他版本,则极有可能必须修改Hibernate配置才能使其正常工作。 但是,我确信它对于所有4.xx版本都可以正常工作。

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.

Hibernate 4使用JBoss日志记录,但是较早的版本使用slf4j进行日志记录,因此我在项目中包含了slf4j-simple工件,尽管由于我使用的是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.

mysql-connector-java是用于连接到MySQL数据库MySQL驱动程序,如果您正在使用任何其他数据库,则添加相应的驱动程序构件。

领域模型类 (Domain Model Classes)

As you can see in above image that we have two model classes, Employee and Employee1.

如上图所示,我们有两个模型类EmployeeEmployee1

Employee is a simple Java Bean class and we will use XML based configuration for providing it’s mapping details.

Employee是一个简单的Java Bean类,我们将使用基于XML的配置来提供其映射详细信息。

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.

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 class is simple java bean, there is nothing specific to discuss here.

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 annotation is used to mark a class as Entity bean that can be persisted by hibernate, since hibernate provides JPA implementation.

javax.persistence.Entity批注用于将类标记为可由hibernate保留的Entity bean,因为hibernate提供了JPA实现。

javax.persistence.Table annotation is used to define the table mapping and unique constraints for the columns.

javax.persistence.Table批注用于定义表映射和列的唯一约束。

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.Id批注用于定义表的主键。 javax.persistence.GeneratedValue用于定义将自动生成该字段,并使用GenerationType.IDENTITY策略,以便将生成的“ id”值映射到bean并可以在java程序中检索。

javax.persistence.Column is used to map the field with table column, we can also specify length, nullable and uniqueness for the bean properties.

javax.persistence.Column用于将字段与表列映射,我们还可以为bean属性指定长度,可为空和唯一性。

Hibernate映射XML配置 (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.

如上所述,我们将基于XML的配置用于Employee类映射。 我们可以选择任何名称,但是为了清楚起见,最好使用表名或Java bean名称。 我们用于Employee bean的Hibernate映射文件如下所示。

employee.hbm.xml

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.

xml配置很简单,并且与基于注释的配置具有相同的作用。

Hibernate配置文件 (Hibernate Configuration Files)

We will create two hibernate configuration xml files – one for xml based configuration and another for annotation based configuration.

我们将创建两个Hibernate配置xml文件-一个用于基于xml的配置,另一个用于基于注释的配置。

hibernate.cfg.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 etcHibernate 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映射文件的配置,我们可以定义多个Hibernate映射文件并在此处配置它们。 另请注意,映射特定于会话工厂。

hibernate-annotation.cfg.xml

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.

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

Hibernate会话工厂 (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.

我创建了一个实用程序类,在该类中,我将从基于XML的配置以及基于属性的配置中创建SessionFactory 。 对于基于属性的配置,我们可以有一个属性文件并在类中读取它,但为简单起见,我在类本​​身中创建Properties实例。

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 configurationprivate static SessionFactory sessionFactory;//Annotation based configurationprivate static SessionFactory sessionAnnotationFactory;//Property based configurationprivate static SessionFactory sessionJavaConfigFactory;private static SessionFactory buildSessionFactory() {try {// Create the SessionFactory from hibernate.cfg.xmlConfiguration 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 swallowedSystem.err.println("Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);}}private static SessionFactory buildSessionAnnotationFactory() {try {// Create the SessionFactory from hibernate.cfg.xmlConfiguration 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 swallowedSystem.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 tooProperties 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.

无论映射是基于XML还是基于注释,为基于XML的配置创建SessionFactory都是相同的。 对于基于属性的属性,我们需要在创建SessionFactory之前在Configuration对象中设置属性并添加注释类。

Overall creating SessionFactory includes following steps:

整体创建SessionFactory包括以下步骤:

  1. Creating Configuration object and configure it创建Configuration对象并对其进行配置
  2. Creating ServiceRegistry object and apply configuration settings.创建ServiceRegistry对象并应用配置设置。
  3. Use configuration.buildSessionFactory() by passing ServiceRegistry object as argument to get the SessionFactory object.通过将ServiceRegistry对象作为参数来使用configuration.buildSessionFactory()以获取SessionFactory对象。

Our application is almost ready now, let’s write some test programs and execute them.

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

Hibernate XML配置测试 (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 SessionSession session = HibernateUtil.getSessionFactory().getCurrentSession();//start transactionsession.beginTransaction();//Save the Model objectsession.save(emp);//Commit transactionsession.getTransaction().commit();System.out.println("Employee ID="+emp.getId());//terminate session factory, otherwise program won't endHibernateUtil.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.

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

Hibernate注释配置测试 (Hibernate Annotation Configuration Test)

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 SessionSessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();Session session = sessionFactory.getCurrentSession();//start transactionsession.beginTransaction();//Save the Model objectsession.save(emp);//Commit transactionsession.getTransaction().commit();System.out.println("Employee ID="+emp.getId());//terminate session factory, otherwise program won't endsessionFactory.close();}}

When we execute above program, we get following output.

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

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]

Have a look at the output and compare it with the output from the XML based configuration, you will notice some differences. For example, we are not setting connection pool size for annotation based configuration, so it’s setting to default value 20.

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

HibernateJava配置测试 (Hibernate Java Configuration Test)

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 SessionSessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();Session session = sessionFactory.getCurrentSession();//start transactionsession.beginTransaction();//Save the Model objectsession.save(emp);//Commit transactionsession.getTransaction().commit();System.out.println("Employee ID="+emp.getId());//terminate session factory, otherwise program won't endsessionFactory.close();}}

Output of the above test program is:

上述测试程序的输出为:

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]

That’s all for hibernate tutorial for beginners, I hope it will be enough to get you started. We will look into different features of Hibernate framework in future tutorials. Download the complete project from below link and play around with it to learn more.

这就是针对初学者的Hibernate教程的全部内容,我希望这足以让您入门。 在以后的教程中,我们将研究Hibernate框架的不同功能。 从下面的链接下载完整的项目,并进行试用以了解更多信息。

Download Hibernate Beginners Project下载Hibernate初学者项目

翻译自: https://www.journaldev.com/2882/hibernate-tutorial-for-beginners

matlab初学者教程

matlab初学者教程_初学者的Hibernate教程相关推荐

  1. javplayer 使用教程_意大利单簧管初级教程报名步骤

    意大利单簧管初级教程报名步骤,在课程的设置方面,北京慧禾国际艺术教育更注重于音乐类专业词汇的培训,加强学生生活口语的实际运用,为学生出国留学打下坚实基础. 意大利单簧管初级教程报名步骤, 在笔者使用过 ...

  2. 计算机系统精品教程,_《计算机操作系统教程》课程教学课件(精品) 设备管理(88P).pdf...

    _<计算机操作系统教程>课程教学课件(精品) 设备管理(88P).pdf 第8章 设备管理 §8.1 引言 §8.2 数据传送控制方式 §8.3 中断技术 §8.4 缓冲技术 §8.5 设 ...

  3. Word教程_编程入门自学教程_菜鸟教程-免费教程分享

    教程简介 Word 2010入门教程 - 从简单的步骤入门Microsoft Office 2010,从基本到高级概念,包括探索窗口,后台视图,输入文本,移动,打开,关闭文档,上下文帮助,插入,选择, ...

  4. Apache POI(Word)教程_编程入门自学教程_菜鸟教程-免费教程分享

    教程简介 IT宝库整理的Apache POI Word入门教程 - 从基本到高级概念的简单简单步骤学习Apache POI Word,其中包括概述,Apache POI安装,核心类,文档,段落,边框, ...

  5. EJB教程_编程入门自学教程_菜鸟教程-免费教程分享

    教程简介 EJB入门教程 - 从简单的步骤了解EJB 3.0和3.1(Enterprise Java Bean)框架,从基本概念到高级概念,包括概述,环境设置,应用服务器,容器,企业Bean,注释,会 ...

  6. 高级Excel功能教程_编程入门自学教程_菜鸟教程-免费教程分享

    教程简介 Excel是办公室自动化中非常重要的一款软件,Excel函数则是Excel中的内置函数.Excel函数共包含11类,分别是数据库函数.日期与时间函数.工程函数.财务函数.信息函数.逻辑函数. ...

  7. weakauras教程_简单的WeakAuras2教程 基础功能设置指南

    玩家分享简单的WeakAuras2插件的基本攻略设置教程,WeakAuras2作为当今的神级插件已经受到了越来越多玩家的使用,WeakAuras2插件除了可以设置简单的技能监视,能量.蓝量的监控以外还 ...

  8. Java国际化教程_编程入门自学教程_菜鸟教程-免费教程分享

    教程简介 Java国际化入门教程 - 从简单的步骤了解Java国际化从基本到高级概念,包括概述,环境设置,区域设置,区域设置详细信息,显示语言,ResourceBundle,NumberFormat, ...

  9. Windows 10教程_编程入门自学教程_菜鸟教程-免费教程分享

    教程简介 Windows 10入门教程 - 从简单的步骤了解Windows 10,从基本到高级概念,包括概述,安装,入门,GUI基础知识,导航,开始菜单,任务栏,平板电脑模式,文件资源管理器,Cort ...

最新文章

  1. oracle 条件反转,Oracle反转倒置函数
  2. 中石油2018年秋季C语言 试卷答案,[石油华东]《数据采集系统》2018年秋季学期在线作业...
  3. 如何应对云爆发架构?四种方法替你解忧
  4. centos 7 构造iptables开放80port
  5. SecureCRT上传bash: rz: command not found
  6. VS2010下多线程的调试(来自MSDN)
  7. jenkins 读取json文件_使用插件轻松获取jenkins构建数据
  8. 利用VisualVm和JMX远程监控K8S里的Java进程
  9. fckeditor php 不显示,PHP Fckeditor上传文件(或图片)中文显示为乱码的解决方法
  10. xp系统从u盘启动计算机,联想xp系统如何设置U盘启动_联想xp通过bios设置U盘启动的步骤...
  11. 《计算机网络基础》笔记 -----应用层(六)
  12. 关于QRCode生成二维码(背景图、Logo)
  13. 微信公众号监听 关注/取消关注事件 消息接收与响应处理(比较细微)
  14. MPLS之LDP的工作原理和配置
  15. hibernate配置映射的问题
  16. linux 读取png图片大小,读取 png 图片的宽高信息
  17. MIRO BAPI_INCOMINGINVOICE_CREATE1 报错 MRM_INVOICE_TAXES_SAVE
  18. vue项目导入谷歌字体包
  19. Kafka从入门到精通(八)Kafka原理
  20. fMRI提取ROI时间序列

热门文章

  1. jquery尺寸:宽度与高度
  2. SWT: 发起事件 post event
  3. [摘抄]游戏主循环逻辑
  4. IOS创建静态库Cocoa Touch Static Library
  5. [转载] python字符串情感分析_python进行情感分析
  6. [转载] python程序所需的图片通过base64编码成字符串放在代码中
  7. [转载] Java中使用new构造数组时会不会自动调用类的默认构造函数
  8. 《Linux就该这么学》培训笔记_ch18_使用MariaDB数据库管理系统
  9. 推荐几本比较好的投资书籍
  10. opencv3 学习三 - 图像输入输出显示等