我们将尝试创建 Hibernate环境并编写执行一个 Hibernate 基本示例。
先决条件
-
Java 1.8
-
IDE
-
Maven 3.5.4
Hibernate 环境设置
安装 Java 1.8 后,我们要设置 eclipse。对于 Maven 安装,请单击此处。Maven 已经在 Eclipse 中进行了设置。所以我们可以在eclipse中创建包含maven的应用程序。或者,如果您愿意,可以单独安装。
安装 Java 1.8 后,我们要设置 eclipse。Maven 安装请点击这里。Maven 已经在 Eclipse 中设置好了。所以我们可以在eclipse中创建包含maven的应用程序。或者,如果您愿意,可以单独安装。
Hibernate 基本示例
CREATE DATABASE IF NOT EXISTS `docsconsole`;
CREATE TABLE IF NOT EXISTS `employees` (
`emp_id` int(11) DEFAULT NULL,
`emp_first_name` varchar(50) DEFAULT NULL,
`emp_last_name` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `employees` (`emp_id`, `emp_first_name`, `emp_last_name`) VALUES
(101, 'Raj', 'Madav'), (102, 'Ram', 'Dev');
请按照以下在 Eclipse 中给出的步骤来创建 Maven Java 项目。
Click on File tab
--> New
--> Click on Maven Project
--> Please check on Create Simple Project (Skip architype selection)
--> Click on Next --> Enter the values docs.console.hibernate.com as Group Id, HibernateFirstExample as Artifact Id
--> Click on Finish
注意:包应该是jar。
现在我们已经成功创建了 Maven Java 项目。
接下来是为员工表创建域/实体类。
Right click on src/main/java
--> New
--> Click on Class
--> Enter value for Package as docs.console.hibernate.com.model and Enter value for Name Employee.
请为 Employee.java 编写下面给出的代码
Employee .java
package docs.console.hibernate.com.model;
public class Employee {
private static final long serialVersionUID = 1L;
private Integer empId;
private String empFirstName;
private String EmpLastName;
public Employee() {
}
public Employee(Integer empId, String empFirstName,String EmpLastName) {
this.empId = empId;
this.empFirstName = empFirstName;
this.EmpLastName = EmpLastName;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpFirstName() {
return empFirstName;
}
public void setEmpFirstName(String empFirstName) {
this.empFirstName = empFirstName;
}
public String getEmpLastName() {
return EmpLastName;
}
public void setEmpLastName(String empLastName) {
EmpLastName = empLastName;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
我们将更新 pom.xml 以获取所需的依赖 jar 文件。
<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.docsconsole.tutorials</groupId>
<artifactId>Hibernate-BasicExample-App-With-XML</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Hibernate-BasicExample-App-With-XML</name>
<dependencies>
<!-- Hibernate 5.4.3.Final -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
<!-- MySql Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- Maven Compiler Plugin -->
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
现在我们将为hibernate创建配置文件。
Right click on src/main/resources
--> New
--> Click on Other
--> select XML File
--> Click Next
--> Enter value for File Name hibernate.cfg.xml
请在 hibernate.cfg.xml 中添加以下给定的 xml 标签。
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/blog?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mappings with hbm xml files -->
<mapping resource="employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
下一步我们将创建类 HibernateMainClient
Right click on src/main/java
--> New
--> Click on Class
--> Enter value for Package as docs.console.hibernate.com and Enter value for Name HibernateMainClient
请在下面找到 HibernateMainClient.java 的给定代码。
package com.docsconsole.tutorials.client;
import com.docsconsole.tutorials.entity.Employee;
import java.util.List;
import com.docsconsole.tutorials.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class HibernateMainClient {
/*static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/docsconsole";
static final String USERNAME = "root";
static final String PASSWORD = "";*/
public static void main(String[] args) {
System.out.println("::::::::::::::::--------------------Started main method here-------------------::::::::::::::::");
SessionFactory sfactory = HibernateUtil.getSessionFactory();
System.out.println("::::::::::::::::--------------------SessionFactory is created here-------------------::::::::::::::::");
Session session = sfactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Employee employee = new Employee();
employee.setEmpFirstName("fname");
employee.setEmpLastName("lname");
session.save(employee);
System.out.println("save Completed !");
System.out.println("::::::::::::::::--------------------Transaction is created here-------------------::::::::::::::::");
Query query = session.createSQLQuery("select emp_id, emp_first_name, emp_last_name FROM employee");
List resultList = query.list();
for (Object object : resultList) {
Object[] objectArray = (Object[]) object;
System.out.println("::::::::::::::::--------------------Employe Id:" + objectArray[0]);
System.out.println("::::::::::::::::--------------------Employe First Name:" + objectArray[1]);
System.out.println("::::::::::::::::--------------------Employe Last Name:" + objectArray[2]);
}
tx.commit();
}
}
为 Employee 实体类创建 hbm 文件。
Right click on docs.console.hibernate.com
--> New
--> Click on Other
--> select XML File
--> Click Next
--> Enter value for File Name Employee.hbm.xml
下面是 Employee.hbm.xml 的 xml 内容
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="docs.console.com.model.Employee" table="employees"
catalog="docsconsole">
<id name="empId" type="java.lang.Integer">
<column name="emp_id" />
<generator class="identity" />
</id>
<property name="empFirstName" type="string">
<column name="emp_first_name" length="10" not-null="true"
unique="true" />
</property>
<property name="EmpLastName" type="string">
<column name="emp_last_name" length="20" not-null="true"
unique="true" />
</property>
</class>
</hibernate-mapping>
现在我们将为 HibernateUtil.java 创建文件
Right click on src/main/java
--> New
--> Click on Class
--> Enter value for Package as docs.console.hibernate.com.util and Enter value for Name HibernateUtil.
请在下面找到 HibernateUtil.java 的给定代码。
package docs.console.hibernate.com.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
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);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
创建项目后,最终架构将如下所示。

NetBeans:

当我们执行 HibernateMainClient 时,我们将得到低于给定的输出。

请在此处参考 Github 存储库Hibernate-BasicExample-App-With-XML
本文介绍如何搭建Hibernate开发环境,并通过一个简单的员工信息管理示例演示Hibernate的基本使用流程,包括配置文件设置、实体映射及数据操作。

1143

被折叠的 条评论
为什么被折叠?



