[SSH] SSH's hibernate framework: initial knowledge of Hibernate

Posted by myshoala on Thu, 06 Feb 2020 08:28:54 +0100

What is Hibernate:

Hibernate is an open-source object relational mapping framework, which encapsulates JDBC with very lightweight objects. It establishes the mapping relationship between POJO and database tables. It is a fully automatic ORM framework. Hibernate can automatically generate SQL statements and execute them, so that Java programmers can use object programming thinking to manipulate the database at will.
ORM: Object Relational Mapping. It refers to establishing a mapping relationship between an object in Java and a table in a relational database, so that the operating object can operate the table in the database.

Why Hibernate:

1. Hibernate encapsulates JDBC objects in a very lightweight way, which greatly simplifies the tedious repetitive code of data access layer, reduces memory consumption and speeds up operation efficiency;
2. Hibernate has excellent performance and excellent mapping flexibility. It supports many relational databases and various complex relationships from one-to-one to many;
3. Open source and API make it extensible.

How to use Hibernate:

Hibernate's download address and directory structure

Download address: https://sourceforge.net/projects/hibernate/files/hibernate-orm/
Directory structure:

documentation: help document for Hibernate development
lib: jar package required for Hibernate development
Project: a project example developed by Hibernate

A simple introduction to Hibernate:

1. Create a Java or web project and import the required jar package:
Database driver package:

Required jar package for Hibernate development:

Logging package:

2. Create a new table in the database: CST "customer

3. Create a new entity class under the package "cn.jingpengchong.pojo": Customer

package cn.jingpengchong.pojo;

public class Customer {
	
	private long id;
	private String name;
	private String source;
	private String industry;
	private String level;
	private String phone;
	private String mobile;
	//To save space, there is no paste get/set method here
	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + ", source=" + source + ", industry=" + industry + ", level="
				+ level + ", phone=" + phone + ", mobile=" + mobile + "]";
	}
}

4. Create the mapping file of entity class Customer under the package "cn.jingpengchong.pojo": Customer.hbm.xml
The dtd of the mapping file can be found in the "/ org/hibernate/hibernate-mapping-3.0.dtd" file of hibernate-core-5.4.10.Final.jar package.
The contents of the mapping file mainly include:
① The class label is used to establish the mapping between class and table;
② Using the id tag to map the id in the class and the primary key in the table, define the primary key generation strategy (to be introduced later);
③ Use the property tag to map common properties in a class to fields in a table.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- Mapping classes and tables -->
	<class name="cn.jingpengchong.pojo.Customer" table="cst_customer">
		<!-- Create the id Mapping to primary key in table -->
		<id name="id" column="cust_id" length="32" type="long">
			<generator class="native"/>
		</id>
		<!-- Establish the mapping between the common properties in the class and the fields in the table -->
		<property name="name" column="cust_name" length="32" type="string"/>
		<property name="source" column="cust_source" length="32" type="string"/>
		<property name="industry" column="cust_industry" length="32" type="string"/>
		<property name="level" column="cust_level" length="32" type="string"/>
		<property name="phone" column="cust_phone" length="64" type="string"/>
		<property name="mobile" column="cust_mobile" length="16" type="string"/>
		
	</class>
</hibernate-mapping>

5. Create Hibernate core configuration file in src Directory: hibernate.cfg.xml
dtd of configuration file can be found in "/ org/hibernate/hibernate-configuration-3.0.dtd" file of hibernate-core-5.4.10.Final.jar package.
The content of the configuration file mainly includes: the name property value of the property tag and the writing format of the tag content can refer to the hibernate.properties file under the directory "hibernate-release-5.4.10.Final\project\etc".
① Use the property tag to declare the necessary configuration: driver, url, user name, password, database jargon, etc. database jargon is used to generate SQL statements that meet the corresponding database standards;
② Use the property tag to declare other configurations: whether to print SQL statements, whether to format SQL statements, whether to automatically create tables, etc;
③ Use the mapping tab to indicate the mapping file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Required configuration -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">1234</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		
		<!-- Optional configuration -->
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		
		<!-- Mapped files -->
		<mapping resource="cn/jingpengchong/pojo/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

6. Create a new package "cn.jingpengchong.test", and create a test class: Test
The main steps are as follows:
① Load configuration file;
② Create a SessionFactory object based on the Configuration object;
③ Obtain a Session object according to the SessionFactory object;
④ Open the Transaction according to the Session object to obtain a Transaction object;
⑤ Perform addition, deletion, modification and query;
⑥ Submit the Transaction according to the Transaction object;
⑦ Release resources.

package cn.jingpengchong.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.jingpengchong.pojo.Customer;

public class Test {
	public static void main(String[] args) {
		//1. Load profile
		Configuration configure = new Configuration().configure();
		//2. Create a SessionFactory based on Configuration
		SessionFactory factory = configure.buildSessionFactory();
		//3. Get a Session object according to SessionFactory
		Session session = factory.openSession();	
		//4. Manually open transaction
		Transaction transaction = session.beginTransaction();		
		//5. Add, delete, modify and query
		Customer customer = new Customer();
		customer.setName("Sun WuKong");
		session.save(customer);		
		//6. Commit transaction
		transaction.commit();		
		//7. Release resources
		session.close();
		factory.close();
	}
}

The operation results are as follows:

Look at the data already in the database:

Hibernate's mapping file and configuration file:

Map file:

Configuration of class tag: used to establish the mapping relationship between class and table
Properties:

  • name: full path of entity class
  • Table: table name
  • catalog: database name, can not be written, specified in the configuration file

Configuration of id tag: used to establish the mapping relationship between an attribute in the class and the primary key in the table
Properties:

  • Name: property name of the class
  • column: field name in the table
  • Length: data length, used when hibernate automatically builds tables
  • Type: data type, used when hibernate automatically builds tables

Configuration of property tag: used to establish the mapping relationship between the properties in the class and the fields in the table
Properties:

  • Name: property name of the class
  • column: field name in the table
  • Length: data length, used when hibernate automatically builds tables
  • Type: data type, used when hibernate automatically builds tables
  • Not null: set non empty, used when hibernate automatically builds tables
  • Unique: set unique, which is used when hibernate automatically builds tables
Profile:

The property tag is used to configure the database parameters: the parameters necessary for using the hibernate framework are the driver class, url, user name, password, and the jargon of the database used. Other important parameters are:
hibernate.show_sql: whether to print SQL statements in the console
Hibernate.format'sql: whether to format the SQL statement when printing it
hibernate.hbm2ddl.auto: automatically create or delete tables

  • none: when the table to be operated does not exist, hibernate will not automatically create a table but report an error;
  • Create: when the table to be operated does not exist, hibernate will automatically create the table. When the table to be operated exists, hibernate will delete the table and create a new table;
  • Create drop: when the table to be operated does not exist, hibernate will automatically create the table, delete the table after use, when the table to be operated exists, hibernate will delete the table, and then recreate a table, delete the table after use;
  • update: when the table to be operated does not exist, hibernate will automatically create the table. When the table to be operated exists, it will use the existing table;
  • validate: when the table to be operated does not exist, hibernate will not automatically create the table but report an error. When the table to be operated exists, the existing table will be used;

The mapping tab indicates the mapping file.

Published 115 original articles, praised 15, visited 1833
Private letter follow

Topics: Hibernate Database Session SQL