Hibernate Framework Notes 01_Environment Build_API_CRUD

Keywords: Hibernate Session Database xml

1. Overview of Hibernate Framework

1.1 What is a Framework

  • Framework: refers to the semi-finished software, has completed some functions.

1.2 Classic Three-tier Architecture

1.3 Hibernate Framework

  • What is hibernate: Hibernate is a persistent ORM framework

  • What is ORM: Object Relational Mapping (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 table in the database can be manipulated by manipulating the object.

2 Hibernate Introduction

2.1 Download Hibernate development kit

  • https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/

  • After decompression:

  • Documentation - --------------- Documentation developed by Hibernate

  • Lib - -------------------------------------- Hibernate development kit

    • Required - --------------------------------------------------------------------------------------------------------------------------------
    • Opti - ------------------------- Hibernate developed the optional jar package
  • Project - ------------------------------------------------- Project provided by Hibernate

2.2 Create projects and introduce jar packages

  • Database driver package mysql

  • hibernate development essential package required

  • hibernate introduces logging packages

2.3 Create tables

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT 'Customer number(Primary key)',
  `cust_name` varchar(32) NOT NULL COMMENT 'Customer name(Corporate name)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT 'Customer Information Sources',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT 'Customer information',
  `cust_level` varchar(32) DEFAULT NULL COMMENT 'Customer level',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT 'Fixed telephone',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT 'Mobile phone',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2.4 Creating Entity Classes

package com.itzhouq.hibernate.demo1;
public class Customer {
	private Long cust_id;
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_phone;
	private String cust_mobile;
    //set/get. . . 

2.5 Create mappings (***)

  • Mapping needs to be done through an XML configuration file, which can be named arbitrarily. Try to unify the naming specification (class name. hbm.xml)

  • New mapping file Customer.hbm.xml under package com.itzhouq.hibernate.demo1

  • Import constraint

    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    
  • Complete mapping file

    <?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>
    	<!-- Create mappings between classes and tables -->
    	<class name="com.itzhouq.hibernate.demo1.Customer" table="cst_customer">
    		<!-- Establishing the correspondence between attributes in classes and primary keys in tables -->
    		<id name="cust_id" column="cust_id">
    			<generator class="native"></generator>
    		</id>
    		
    		<!-- Establishing the correspondence between common attributes in tables and fields in tables -->
    		<property name="cust_name" column="cust_name"></property>
    		<property name="cust_source" column="cust_source"></property>
    		<property name="cust_industry" column="cust_industry"></property>
    		<property name="cust_level" column="cust_level"></property>
    		<property name="cust_phone" column="cust_phone"></property>
    		<property name="cust_mobile" column="cust_mobile"></property>
    	</class>
    	
    </hibernate-mapping>
    

2.6 Create a core configuration file for Hibernate (***)

  • The name of Hibernate's core configuration file: hibernate.cfg.xml

  • New core configuration file hibernate.cfg.xml under src, import constraints

  • Configuration core file, connection database, username, password and other information can be referred to the file. \ Hibernate-release-5.0.7. Final hibernate-release-5.0.7. Final project etc hibernate. properties Fifty-one lines

    <?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>
    		<!-- Basic parameters for connecting databases -->
    		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    		<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
    		<property name="hibernate.connection.username">root</property>
    		<property name="hibernate.connection.password">2626</property>
    		
    		<!-- To configure Hibernate Dialects (optional) -->
    		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    		<!-- Printing SQL(Optional) -->
    		<property name="hibernate.show_sql">true</property>
    		<!-- Format SQL(Optional) -->
    		<property name="hibernate.format_sql">true</property>
    		
    		<!-- Configuration mapping file -->
    		<mapping resource="com/itzhouq/hibernate/demo1/Customer.hbm.xml"/>
    		
    	</session-factory>
    </hibernate-configuration>
    

1.2.7 Write test code

package com.itzhouq.hibernate.demo1;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class HIbernateDemo1 {
	
	//Case of Customer Preservation
	@Test
	public void demo1() {
		// 1. Loading hibernate's core configuration file
		Configuration configure = new Configuration().configure();
		// 2. Create a SessionFactory object: a connection pool similar to JDBC
		SessionFactory sessionFactory = configure.buildSessionFactory();
		// 3. Getting Session objects through SessionFactory: Similar to Connection in JDBC
		Session session = sessionFactory.openSession();
		// 4. Manual Opening of Transactions
		Transaction transaction = session.beginTransaction();
		// 5. Coding
		Customer customer = new Customer();
		customer.setCust_name("Lao Wang");
		
		session.save(customer);
		// 6. Submission
		transaction.commit();
		// 7. Releasing resources
		session.close();
	}
}

3 hibernate common configuration

3.1 Hint Configuration of XML

  • Advance replication configuration connection http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd

  • Configure in the following order

  • The prompt configuration method of the core configuration file is similar

3.2 Configuration of Hibernate Mapping

<?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>
	<!-- Create mappings between classes and tables -->
	<class name="com.itzhouq.hibernate.demo1.Customer" table="cst_customer">
		<!-- Establishing the correspondence between attributes in classes and primary keys in tables -->
		<id name="cust_id" column="cust_id">
			<generator class="native"></generator>
		</id>
		
		<!-- Establishing the correspondence between common attributes in tables and fields in tables -->
		<property name="cust_name" column="cust_name"></property>
		<property name="cust_source" column="cust_source"></property>
		<property name="cust_industry" column="cust_industry"></property>
		<property name="cust_level" column="cust_level"></property>
		<property name="cust_phone" column="cust_phone"></property>
		<property name="cust_mobile" column="cust_mobile"></property>
	</class>
	
</hibernate-mapping>
  • Configuration of class Tags
    • Labels are used to establish mapping relationships between classes and tables
    • Properties:
      • Name------------------------- The full path name of the class
      • Table - ----------- table name (table can be omitted when class name is consistent with table name)
      • catalog - ----- database name
  • Configuration of id tags
    • Labels are used to establish the correspondence between attributes in classes and primary keys in tables.
    • Properties:
      • name----------------------------- attribute names in classes
      • column - --------- Field names in tables (properties in classes and field names in tables can be omitted if they are identical)
      • length---------------- length
      • type----------------- type
  • property Label Configuration
    • Tags are used to establish the correspondence between common attributes in classes and fields in tables.
    • Properties:
      • name----------------------------- attribute names in classes
      • column------------- field names in tables
      • length---------------- length
      • type----------------- type
      • not-null - ----- Set non-empty
      • Unique - ----------------------- Set unique

3.3 Core configuration of Hibernate

  • Necessary Configuration--Basic Parameters for Connecting Database
    • Driver class
    • url path
    • User name
    • Password
  • Optional configuration
    • Display SQL - ----------- hibernate. show_sql
    • Formatting SQL - ----- hibernate. format_sql
    • Automatic table building - ----------- hibernate.hbm2ddl.auto
      • Update: If there are tables in the database, use the original table, and if there are no tables, create a new table (update table structure)
      • validate: If there are no tables, no tables will be created. Only the original tables in the database will be used. Check mapping and table structure.
      • none: Automatic table building without hibernate
      • Create: If there are already tables in the database, delete the original tables and recreate them. If there are no tables, create new tables. (test)
      • create-drop: If a table already exists in the database, delete the original table, perform the operation, and delete the table. If there is no table, create a new one and delete the table after use. (test)
  • Introduction of Mapping Files
    • Location of introducing mapping files

4. Hibernate's core API

4.1 Configuration: Hibernate's Configuration Object

  • Effect:

    • Load the core configuration file

      // 1. Loading hibernate's core configuration file
      		Configuration configure = new Configuration().configure();
      
    • Load the mapping file

      <!-- Configuration mapping file -->
      		<mapping resource="com/itzhouq/hibernate/demo1/Customer.hbm.xml"/>
      
  • The Configuration class configures Hibernate and starts it. During hibernate startup, an instance of the Configuration class first locates the mapping file, reads the configuration, and then creates a SessionFactory object. Although the Configuration class only plays a small role in the entire Hibernate project, it is the first object encountered when starting Hibernate.

4.2 Session Factory: Session Factory

  • The SessionFactory interface is responsible for initializing Hibernate. It acts as a proxy for data storage sources and is responsible for creating Session objects. The factory model is used here. Xu Ya noticed that SessionFactory is not lightweight, because in general, only one SessionFactory is needed for a project. When multiple databases need to be operated, one SessionFactory can be specified for each database.

  • Session Factory maintains Hibernate's connection pool and Hibernate's secondary cache (not to mention). Is a thread-safe object. Create an object for a project.

  • Configure connection pool and extract tool classes

    • Import the jar package of c3p0... \ hibernate-release-5.0.7.Finalhibernate-release-5.0.7.Finalliboptionalc3p0
      • c3p0-0.9.2.1.jar
      • hibernate-c3p0-5.0.7.Final.jar
      • mchange-commons-java-0.2.3.4.jar
    • In the main configuration file, add the following configuration
    <! - Configure the C3P0 connection pool - >.
    		<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
    		<! - The minimum number of database connections available in connection pools - >
    		<property name="c3p0.min_size">5</property>
    		<! - The maximum number of database connections in the connection pool - >
    		<property name="c3p0.max_size">20</property>
    		<! - Set the expiration time of the database connection in seconds.
    		If a database connection in the connection pool is idle for more than timeout time, it will be cleared from the connection pool - >
    		<property name="c3p0.timeout">120</property>
    		 <! - Check free connections in all connection pools every 3,000 seconds in seconds - >
    		<property name="c3p0.idle_test_period">3000</property>
    
    • Create a new package, create a tool class HibernateUtils.java

      package com.itzhouq.hibernate.utils;
      
      import org.hibernate.Session;
      import org.hibernate.SessionFactory;
      import org.hibernate.cfg.Configuration;
      
      /*
       * Hibernate Tool class
       */
      public class HibernateUtils {
      	public static final Configuration cfg;
      	public static final SessionFactory sf;
      	
      	static {
      		cfg = new Configuration().configure();
      		sf = cfg.buildSessionFactory();
      	}
      	
      	public static Session openSession() {
      		return sf.openSession();
      	}
      }
      
    • After configuration, the code for the test class is greatly simplified

      package com.itzhouq.hibernate.demo1;
      /*
       * Hibernate Tool class testing
       */
      
      import org.hibernate.Session;
      import org.hibernate.Transaction;
      import org.junit.Test;
      
      import com.itzhouq.hibernate.utils.HibernateUtils;
      
      public class HibernateDemo2 {
      	
      	@Test
      	//Save customers
      	public void demo1() {
      		Session session = HibernateUtils.openSession();
      		Transaction tx = session.beginTransaction();
      		
      		Customer customer = new Customer();
      		customer.setCust_name("Wang Xiaodong");
      		Serializable id = session.save(customer);
      		System.out.println("id = " + id);//1
      		tx.commit();
      		session.close();
      	}
      }
      

4.3 Session: Connection-like objects are connection objects

  • The session interface is responsible for performing CRUD operations on persistent objects. However, it should be noted that session objects are non-thread-safe. At the same time, Hibernate session is different from HTTP Session in JSP applications. The session here is similar to Connection.

  • API in Session

    • Preservation method:

      • Serializable save(Object obj);

        @Test
        	//Save customers
        	public void demo1() {
        		Session session = HibernateUtils.openSession();
        		Transaction tx = session.beginTransaction();
        		
        		Customer customer = new Customer();
        		customer.setCust_name("Wang Xiaodong");
        		Serializable id = session.save(customer);
        		System.out.println("id = " + id);//1
        		
        		tx.commit();
        		session.close();
        	}
        
    • Query method

      • T get(Class c, Serializable id)

      • T load(Class c, Serializable id)

        @Test
        	//Query method
        	public void demo2() {
        		Session session = HibernateUtils.openSession();
        		Transaction tx = session.beginTransaction();
        		
        //		Customer customer = session.get(Customer.class, 1L);
        //		System.out.println(customer);
        		
        		Customer customer = session.load(Customer.class, 1L);
        		System.out.println(customer);
        		
        		tx.commit();
        		session.close();
        	}
        
      • The difference between get method and load method

      • get:

        1. The method is to load the code immediately and send sql statement to query it immediately when the code is executed.
        2. The query returns a real object itself.
        3. When querying an object that cannot be found, return null.
      • load:

        1. The lazy lazy loading is adopted. When this line of code is executed, the SQL statement will not be sent immediately, but the SQL statement will only be sent when the object is actually used.
        2. The proxy object returned after sweat search is used to generate the proxy by javassist technology.
        3. When querying an object that cannot be found, an exception is thrown.
    • Modification method

      • void update(Object obj)

    • Deletion method

      • void delete(Object obj)

    • Query all

4.4 Transaction: Transaction object

  • Objects that manage transactions in Hibernate
    • commit()
    • rollback()

Posted by nadnad on Mon, 22 Apr 2019 17:51:35 -0700