Learning Log-2019/08/16

Keywords: Programming Hibernate Session Database xml

Introduction to Hibernate

Download Hibernate development environment


documentation: documentation developed by Hibernate
lib: Hibernate development kit
required: Necessary dependency packages for Hibernate development
Optional: An optional jar package developed by Hibernate
project: project provided by Hibernate

Create a project to introduce the jar package

  • Database Driver Package
  • Necessary packages for Hibernate development
  • Hibernate's Pack for Introducing Logs

Building 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;

Create entity classes

  • Customer
package hibernatedemo01;
/**
 *Customer Management Entity Class
 */
public class Customer {
	private Long cust_id;		//Customer Number (Primary Key)
	private String cust_name;	//Customer Name (Company Name)
	private String cust_source; //Customer Information Sources
	private String cust_industry;//Customer Information
	private String cust_level;	 //Customer Level
	private String cust_phone;	 //Fixed telephone
	private String cust_mobile;	 //Mobile phone
	public Long getCust_id() {
		return cust_id;
	}
	public void setCust_id(Long cust_id) {
		this.cust_id = cust_id;
	}
	public String getCust_name() {
		return cust_name;
	}
	public void setCust_name(String cust_name) {
		this.cust_name = cust_name;
	}
	public String getCust_source() {
		return cust_source;
	}
	public void setCust_source(String cust_source) {
		this.cust_source = cust_source;
	}
	public String getCust_industry() {
		return cust_industry;
	}
	public void setCust_industry(String cust_industry) {
		this.cust_industry = cust_industry;
	}
	public String getCust_level() {
		return cust_level;
	}
	public void setCust_level(String cust_level) {
		this.cust_level = cust_level;
	}
	public String getCust_phone() {
		return cust_phone;
	}
	public void setCust_phone(String cust_phone) {
		this.cust_phone = cust_phone;
	}
	public String getCust_mobile() {
		return cust_mobile;
	}
	public void setCust_mobile(String cust_mobile) {
		this.cust_mobile = cust_mobile;
	}
	
}

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)

<?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>
	<!-- Establishing Mapping Between Classes and Tables -->
	<class name="hibernatedemo01.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"/>
		</id>
		
		<!-- Establish the correspondence between common attributes in classes and fields in tables -->
		<property name="cust_name" column="cust_name" length="32" />
		<property name="cust_source" column="cust_source" length="32"/>
		<property name="cust_industry" column="cust_industry"/>
		<property name="cust_level" column="cust_level"/>
		<property name="cust_phone" column="cust_phone"/>
		<property name="cust_mobile" column="cust_mobile"/>
	</class>
</hibernate-mapping>

Create a core configuration file for Hibernate

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

<?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 database -->
		<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
		<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/hibernate?useSSL=false &amp;serverTimezone=Asia/Shanghai</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<!-- To configure Hibernate Dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<!-- Optional configuration================ -->
		<!-- Printing SQL -->
		<property name="hibernate.show_sql">true</property>
		<!-- Format SQL -->
		<property name="hibernate.format_sql">true</property>
		
		
		
		<mapping resource="hibernatedemo01/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

Write test code

package hibernatedemo01;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.Test;
/**
 * Hibernate An introduction to the case study of ____________
 * @author Administrator
 *
 */
public class HibernateDemo01 {
	
	@Test
	//Case of Customer Preservation
	public void demo1() {
		//1. Loading Hibernate's Core Profile
		Configuration configuration=new Configuration().configure();
		//2. Create a SessionFactory object, similar to the connection pool in JDBC
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//3. Getting Session objects through SessionFactory is 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("Zhang San");
		session.save(customer);
		
		//6. Transaction submission
		transaction.commit();
		
		//7. Resource release
		session.close();
	}
}

Common configuration of Hibernate

  • Configuration of XML Tips
    • Configuring XML prompts

  • Configuration of Hibernate Mapping
    Configuration of mappings
  • [class Label Configuration]
	Labels are used to establish mapping relationships between classes and tables
	Attributes:
	name: the full path of the class
	Table: Table name (class name is the same as table name, table can be omitted)
	catalog: database name
  • [Configuration of id tags]
	Labels are used to establish the correspondence between attributes in classes and primary keys in tables.
	Attributes:
	name: attribute names in classes
	Column: Field names in tables (column can be omitted if attribute names in classes and field names in tables are identical)
	length: length
	type: type
  • [property Label Configuration]
	Labels are used to establish the correspondence between common attributes in classes and fields in tables.
	Attributes:
	name: attribute names in classes
	column: field names in tables
	length: length
	type: type
	not-null: Set non-null
	Unique: Set unique

Core configuration of Hibernate

  • Hibernate's Core Configuration
    • One way: Attribute file
	hibernate.properties
	hibernate.connection.driver_class=com.mysql.jdbc.Driver
	...
	hibernate.show_sql=true
	Property files cannot be introduced in a mapping file (manually writing code to load the mapping file)
  • Two ways: XML file
    hibernate.cfg.xml

Core configuration

  • Necessary configuration
    • Basic parameters for connecting databases
#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password
  1. Driver class
  2. url path
  3. User name
  4. Password
  5. dialect
<!-- To configure Hibernate Dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  • Optional configuration
  1. Display SQL: hibernate.show_sql
  2. Formatting SQL: hibernate.format_sql
  3. Automatic table building: hibernate.hbm2ddl.auto
    	none: Automatic table building without hibernate
    	Create: If there are already tables in the database, delete the original tables, recreate them, and if there are no tables, create new tables. (Testing)
    	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. (Testing)
    	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.
  • Introduction of mapping file
    • Location of introducing mapping files

Hibernate's core API

Hibernate has six API s: Session, Session Factory, Transaction, Query, Criteria and Configuration. Through these interfaces, persistent objects can be accessed and transacted.

Configuration: Hibernate's configuration object

The Configuration class configures Hibernate and starts it. During the start-up of Hibernate, an instance of the Configuration class first locates the mapping document, 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.

  • Effect:
    • Load the core configuration file
      • hibernate.properties
Configuration cfg = new Configuration();
  • hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
  • Load the mapping file
    // Manual loading mapping
configuration.addResource("hibernatedemo01/Customer.hbm.xml");
Session Factory: Session Factory

SessionFactory
SessionFactory Interface is responsible for initialization Hibernate. It acts as a proxy for data storage sources and is responsible for creating Session Object. The factory model is used here. Notice that SessionFactory It's not lightweight, because in general, only one project is needed. SessionFactory That's enough. When you need to operate on multiple databases, you can specify one for each database. SessionFactory.

  • Configuring connection pools: (Understanding)
<! - Configure the C3P0 connection pool - >.
		<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<! - Minimum number of database connections available in connection pool - >
		<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 3000 seconds in seconds - >
		<property name="c3p0.idle_test_period">3000</property>
		
  • Extraction Tool Class
package hibernate.utils;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate Tool class
 * @author jt
 *
 */
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();
	}
}

Session: Connection-like objects are connection objects

Session
Session Interfaces are responsible for executing persisted objects CRUD operation(CRUD The task is to communicate with the database, including many common ones. SQL Sentence). But it should be noted that Session Objects are non-thread-safe. At the same time, Hibernate Of session Differ JSP In application HttpSession. This should be used here. session When this term is used, it actually refers to Hibernate Medium session,Later, it will be HttpSession Objects are called users session.

  • API in Session
    • Preservation method:
       Serializable save(Object obj);
    • Query method:
       T get(Class c,Serializable id);
       T load(Class c,Serializable id);
  • What is the difference between get method and load method?
	package hibernatedemo01;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import hibernate.utils.HibernateUtils;

/**
 * Hibernate Tool class testing
 * @author jt
 *
 */
public class HibernateDemo02 {

	@Test
	// Customer Preservation
	public void demo1(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		Customer customer  = new Customer();
		customer.setCust_name("Wang Xiaoxi");
		Serializable id = session.save(customer);
		System.out.println(id);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// Query:
	// Differences between *** get method and load method
	public void demo2(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		/**
		 * get Method
		 * 	* The method is to load it immediately, and when you execute this line of code, you will send an SQL statement to query it immediately.
		 *  * The return after the query is the real object itself.
		 * 	* When querying an object that cannot be found, return null
		 * 
		 * load Method
		 * 	* Lazy lazy loading is adopted. When this line of code is executed, no SQL statement will be sent, and only when the object is actually used will the SQL statement be sent.
		 *  * The proxy object is returned after the query. javassist-3.18.1-GA.jar uses the proxy generated by javassist technology.
		 *  * When querying an object that cannot be found, return ObjectNotFoundException
		 */
		// Query with get method
		/*Customer customer = session.get(Customer.class, 100l); // Send SQL statements
		System.out.println(customer);*/
		
		// Using load method to query
		Customer customer = session.load(Customer.class, 1l);
		System.out.println(customer);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// Modification operation
	public void demo3(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		// Create objects directly and modify them
		/*Customer customer = new Customer();
		customer.setCust_id(1l);
		customer.setCust_name("Wang Cong;
		session.update(customer);*/
		
		// First query, then modify (recommend)
		Customer customer = session.get(Customer.class, 1l);
		customer.setCust_name("forget you anyway");
		session.update(customer);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// Delete operation
	public void demo4(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		// Create objects directly, delete them
	/*	Customer customer = new Customer();
		customer.setCust_id(1l);
		session.delete(customer);*/
		
		// Query and Delete (Recommendation) -- Cascading Delete
		Customer customer = session.get(Customer.class, 2l);
		session.delete(customer);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// Save or update
	public void demo5(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		/*Customer customer  = new Customer();
		customer.setCust_name("Wang Feng;
		session.saveOrUpdate(customer);*/
		
		Customer customer = new Customer();
		customer.setCust_id(3l);
		customer.setCust_name("Li Ruhua");
		session.saveOrUpdate(customer);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// Query all
	public void demo6(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		// Receiving HQL: Hibernate Query Language Object-Oriented Query Language
		/*Query query = session.createQuery("from Customer");
		List<Customer> list = query.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}*/
		
		// Receive SQL:
		SQLQuery query = session.createSQLQuery("select * from cst_customer");
		List<Object[]> list = query.list();
		for (Object[] objects : list) {
			System.out.println(Arrays.toString(objects));
		}
		tx.commit();
		session.close();
	}
}

Transaction: Transaction object
  • Objects that manage transactions in Hibernate.
    • commit();
    • rollback();

Posted by Braclayrab on Fri, 16 Aug 2019 07:09:46 -0700