hibernate入门教程_hibernate还有人用吗

(2) 2024-07-23 09:23

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
hibernate入门教程_hibernate还有人用吗,希望能够帮助你!!!。

 

Hibernate初学者教程

 

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

目录[ 隐藏 ]

  • 1初学者的Hibernate教程
    • 1.1 Hibernate架构
    • 1.2 Hibernate和Java Persistence API(JPA)
  • 2休眠示例
    • 2.1数据库表设置
    • 2.2 Hibernate项目依赖项
    • 2.3域模型类
    • 2.4 Hibernate映射XML配置
    • 2.5休眠配置文件
    • 2.6 Hibernate SessionFactory
    • 2.7 Hibernate XML配置测试
    • 2.8 Hibernate注释配置测试
    • 2.9 Hibernate Java配置测试

Hibernate初学者教程

如果你看一下JDBC代码,就会有很多样板代码,并且存在资源泄漏和数据不一致的可能性,因为所有工作都需要由开发人员完成。这是ORM工具的便利之处。

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

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

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

我希望上述所有好处都能说服您,Hibernate是您的应用程序对象关系映射要求的最佳选择。现在让我们看一下Hibernate Framework架构,然后我们将跳转到示例项目中,我们将研究在独立Java应用程序中配置Hibernate并使用它的不同方法。

Hibernate架构

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

让我们逐个看一下hibernate架构的核心组件。

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

Hibernate和Java Persistence API(JPA)

Hibernate提供了Java Persistence API的实现,因此我们可以将JPA注释与模型bean一起使用,而hibernate将负责将其配置为在CRUD操作中使用。我们将使用注释示例来研究这个问题。

Hibernate示例

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

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

我们的最终项目将如下图所示。

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

数据库表设置

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

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

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

Hibernate项目依赖项

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

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://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包含所有核心hibernate类,因此我们将通过将其包含在项目中来获得所有必需的功能。

请注意,我正在为我的示例项目使用最新的Hibernate版本(4.3.5.Final),Hibernate仍在不断发展,我看到很多核心类在每个主要版本之间都会发生变化。因此,如果您使用的是任何其他版本,则很可能您必须修改Hibernate配置才能使其正常工作。但是,我确信它对所有4.xx版本都可以正常工作。

Hibernate 4使用JBoss日志记录,但旧版本使用slf4j进行日志记录,因此我在项目中包含了slf4j-simpleartifact,尽管不需要,因为我使用的是Hibernate 4。

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

域模型类

正如您在上面的图像中看到的那样,我们有两个模型类,Employee并且Employee1

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

Employee1是一个java bean,其中的字段用JPA注释注释,因此我们不需要在单独的XML文件中提供映射。

 package com.journaldev.hibernate.model; import java.util.Date; public class Employee { private int id; private String name; private String role; private Date insertTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Date getInsertTime() { return insertTime; } public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } } 

Employee类是简单的java bean,这里没有具体讨论。

 package com.journaldev.hibernate.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name="Employee", uniqueConstraints={ 
   @UniqueConstraint(columnNames={ 
   "ID"})}) public class Employee1 { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="ID", nullable=false, unique=true, length=11) private int id; @Column(name="NAME", length=20, nullable=true) private String name; @Column(name="ROLE", length=20, nullable=true) private String role; @Column(name="insert_time", nullable=true) private Date insertTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Date getInsertTime() { return insertTime; } public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } } 

javax.persistence.Entity 注释用于将类标记为可以由hibernate持久化的实体bean,因为hibernate提供了JPA实现。

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

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

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

Hibernate映射XML配置

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

employee.hbm.xml

 <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.journaldev.hibernate.model.Employee" table="EMPLOYEE"> <id name="id" type="int"> <column name="ID" /> <generator class="increment" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="role" type="java.lang.String"> <column name="ROLE" /> </property> <property name="insertTime" type="timestamp"> <column name="insert_time" /> </property> </class> </hibernate-mapping> 

xml配置很简单,与基于注释的配置完全相同。

休眠配置文件

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

的hibernate.cfg.xml

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

大多数属性与数据库配置相关,其他属性详细信息在注释中给出。注意hibernate映射文件的配置,我们可以定义多个hibernate映射文件并在这里​​配置它们。另请注意,映射特定于会话工厂。

冬眠,annotation.cfg.xml

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

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

 

Hibernate SessionFactory

我创建了一个实用程序类,我SessionFactory从基于XML的配置和基于属性的配置创建。对于基于属性的配置,我们可以有一个属性文件并在类中读取它,但为了简单起见,我在类本​​身中创建了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 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; } } 

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

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

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

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

Hibernate XML配置测试

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

 package com.journaldev.hibernate.main; import java.util.Date; import org.hibernate.Session; import com.journaldev.hibernate.model.Employee; import com.journaldev.hibernate.util.HibernateUtil; public class HibernateMain { public static void main(String[] args) { Employee emp = new Employee(); emp.setName("Pankaj"); emp.setRole("CEO"); emp.setInsertTime(new Date()); //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(); } } 

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

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

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

Hibernate注释配置测试

 package com.journaldev.hibernate.main; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.journaldev.hibernate.model.Employee1; import com.journaldev.hibernate.util.HibernateUtil; public class HibernateAnnotationMain { public static void main(String[] args) { Employee1 emp = new Employee1(); emp.setName("David"); emp.setRole("Developer"); emp.setInsertTime(new Date()); //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初学者项目

 

转载来源:https://www.journaldev.com/2882/hibernate-tutorial-for-beginners

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复