0. structure diagram
1. Writing rules for persistent classes
1.1 Persistence and Persistence Classes
- Persistence: The process of persisting an object in memory to a database. The Hibernate framework is the framework for persistence.
- Persistence class: A Java object maps to a database table, so this class is called a persistence class in Hibernate.
- Persistence = Java class + mapping file
1.2 Writing rules for persistent classes
- Provides a parametric approach to persistence: the underlying HIbernate needs to use reflection to generate instances.
- Attributes need to be privatized, providing public get and set methods for private attributes: get in Hibernate, set the value of the object.
- Provide a unique identifier for persistence that OID corresponds to the database primary key: is it the same object in Java by distinguishing the address of the object, is it the same record in the database by the primary key, and is it the same object in Hibernate by distinguishing the OID attribute of the persistence class?
- Attributes in persistent classes use wrapper types as much as possible: because the default value of the basic data type is 0, then 0 will have many ambiguities. The default value of the packaging type is null.
- Persistence classes should not be modified with final: latency is itself an optimization tool for Hibernate. Returns a proxy object that generates proxies for classes that do not implement interfaces. This proxy uses very low-level bytecode enhancement techniques to inherit this class for proxy. If it cannot be inherited and proxy objects cannot be generated, the delay will be invalid. The load and get methods are consistent.
2. Primary Key Generation Strategy
Classification of 2.1 Primary Bonds
- Natural Primary Key:
- The primary key itself is a field in a table (a specific attribute in an entity).
- To create a personnel table, people will have an ID number (the only non-repeatable), using the ID number as the primary key, which is called the natural primary key.
- Agent primary key:
- The primary key itself is not a required field in the table (not a specific property in the entity)
- Create a staff table that does not use the ID number in the staff to use a field ID that is not related to the table. This primary key is called the proxy primary key.
- In the actual development, try to use the proxy primary key
- Once the natural primary key is involved in the business logic, it may be necessary to modify the source code later.
- Good programming satisfies the OCP principle, open s when extending the program, close s when modifying the original Amen.
2.2 Primary Key Generation Strategy
- In practical development, users are generally not allowed to set the primary key manually. They usually hand the primary key to the database and write programs manually to set it. In Hibernate, there are many primary key generation strategies to reduce programming.
- increment: The automatic growth mechanism provided in Hibernate applies to short, int, long primary keys. Used in single-threaded programs.
- First send an Sql statement: select max(id) from table; then let id +1 be the primary key of the next record
- identity: Primary keys for short, int, long types, using the automatic growth mechanism at the bottom of the database. It is suitable for databases with automatic growth mechanism (Mysql, MSSQL), but Oracle does not grow automatically.
- Sequence: Suitable for short, int, long type primary keys, using the time sequence approach. Oracle supports sequences, but Mysql cannot use sequences.
- uuid: Suitable for string type primary keys. Use Hibernate to generate string primary keys randomly.
- native: The local policy allows automatic switching between identity and sequence.
- Assignment: hibernate abandons the management of foreign keys and needs to write programs manually or set up by itself.
- foreign: External. Used in the case of one-to-one association mapping. (understanding)
3. Three states of persistent classes [Understanding]
3.1 Three states of persistent classes
- Hibernate time persistence layer framework, through the persistence class to complete ORM operations. Hibernate divides persistence classes into three states in order to better manage persistence classes.
- Persistent class = Java class + mapping
- Transient: This object has no unique identifier OID and is not managed by session. It is called transient object.
-
Persistent state: This object has a unique identifier, OID, and is managed by session. It is called a persistent state object.
- Persistent objects of persistent classes can automatically update databases
- Managed state: This object has a unique identifier OID and is not managed by session. It is called a managed state object.
3.2 Distinguish three persistent states
@Test //Differentiation of three states public void demo1() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); Customer customer = new Customer(); // Transient object: No unique ID OID, no session management customer.setCust_name("Wang Xiaodong"); Serializable id = session.save(customer); // Persistent object: Unique ID OID, managed by session tx.commit(); session.close(); System.out.println("Customer Name: " + customer.getCust_name()); // Managed object: Unique ID OID, not session managed }
3.3 Transition of three persistent states
3.3.1 Three State Transition Diagrams of Persistent States
3.3.2 Transient Objects
- Get:
- Customer customer = new Customer();
- state transition
- Instantaneous - > Persistent
- save(Obejct obj),saveOrUpdate(Object obj);
- Instantaneous - --> Trusteeship
- customer.setCust_id(1);
- Instantaneous - > Persistent
3.3.3 persistent state
- Get
- get(),load(),find(),iterate()
- Customer customer = session.get(Customer.class,1L);
- state transition
- Persistence - --> Instantaneous
- delete()
- Persistence - --> Trusteeship
- close(),clear(),evict(Object obj)
- Persistence - --> Instantaneous
3.3.4 Managed Objects
- Get
- Customer customer = new Customer();
- customer.setCust_id(1L);
- state transition
- Trusteeship - > Persistence
- update(), saveOrUpdate()
- Trusteeship - --> Instantaneous
- customer.setCust_id(null)
- Trusteeship - > Persistence
Characteristics of 3.3.5 Persistent Objects
@Test // Persistent object updates database automatically public void demo2() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // Get persistent objects: Customer customer = session.get(Customer.class, 1L); customer.setCust_name("Wang Lama"); //session.update(customer); // If you don't write this sentence, you can also save the data to the database. This is the characteristic of persistent objects. The bottom layer is the first level cache. transaction.commit(); session.close(); }
4. Hibernate's Level 1 Cache
4.1 Cache Overview
- What is caching?
- Caching is an optimized way to store data in memory and use it directly from the cache without using the storage source.
4.2 hibernate Cache
- Hibernate framework provides a lot of optimization tools, such as caching, crawling strategies. Hibernate provides two caching mechanisms, first-level caching and second-level caching.
- Hibernate's first level cache refers to the Session cache. Session cache is a memory space for storing mutually managed Java objects. When using Hibernate to query objects, the OID value of object attributes is first searched in Hibernate's first level cache. If a matching OID is found to be worth the object, the object will be taken out of the first level cache directly. Query the database again; if you do not find the same OID worthy object, you will go to the database to find the corresponding data. When the required data is queried from the data, the data information is also placed in the first-level cache. Hibernate's first-level caching function is to reduce the number of visits to the database.
- A series of Java collections are included in the implementation of the Session interface, which constitute the Session cache. As long as the Session instance does not end its life cycle, objects stored in its cache do not end its life cycle. So the first level cache is also called Session's basic cache.
- Hibernate's secondary cache is a Session Factory level cache that needs to be configured. Secondary caching has been replaced by Redis and will not be used in the actual development process.
- The first level cache is self-contained and can not be uninstalled.
4.3 Prove the existence of the first level cache
package com.itzhouq.hibernate.demo1; import java.io.Serializable; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.itzhouq.hibernate.utils.HibernateUtils; public class Demo3 { // Prove the existence of the first level cache @Test public void test() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); // Customer customer1 = session.get(Customer.class, 1L); // Send SQL statements // System.out.println(customer1); // // Customer customer2 = session.get(Customer.class, 1L); // Do not send SQL statements // System.out.println(customer2); Customer customer = new Customer(); customer.setCust_name("Miss Luo Yu Feng"); Serializable id = session.save(customer); Customer customer2 = session.get(Customer.class, id); // Do not send SQL statements System.out.println(customer2); transaction.commit(); session.close(); } }
4.4 Level 1 Cache Structure
5. Hibernate transaction management
5.1 What is a transaction?
- Transaction: A transaction is a logical set of operations whose logical units either succeed or fail.
5.2 Transaction Characteristics
- Atomicity: Represents the inseparability of affairs.
- Consistency: Data integrity is consistent before and after transaction execution.
- Isolation: Represents a transaction in the execution process, should not be interfered by other transactions.
- Persistence: Data is persisted to the database on behalf of transaction execution.
5.3 Failure to consider isolation causes security problems
- Reading questions:
- Dirty reading: One transaction reads uncommitted data from another transaction.
- Non-repeatable reading: One transaction reads update data already submitted by another transaction, resulting in inconsistent results of multiple queries in the previous transaction.
- Dummy reading: One transaction reads insert data already submitted by another transaction, resulting in inconsistent results of multiple queries in the previous transaction.
- Writing Questions [Understanding]
- Causing two types of lost updates
5.4 Reading Problem Solution
- Setting transaction isolation level
- Read uncommitted: The above reading problems will occur
- Read committed: Resolve dirty reading, but non-repeatable reading and virtual reading may occur (Oracle)
- Repeatable read: Resolves dirty reading and non-repeatable reading, but virtual reading may occur (Mysql)
- Serlializable: Solve all reading problems
5.5 Set transaction isolation level
-
Add the following configuration to the main configuration file
<! - Set the isolation level for transactions - > <property name="hibernate.connection.isolation">4</property>
4 is the default level for MySQL database
-
Corresponding relationship between number and isolation level
- 1----------Read uncommitted isolation
- 2----------Read committed isolation
- 4----------Repeatable read isolation
- 8----------Serializable isolation
5.6 Hibernate Solves Service Transaction Management
-
Transactions at Service Layer
-
Code and configuration
-
Rewrite the tool class and add the getCurrentSession() order
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(); } public static Session getCurrentSession() { return sf.getCurrentSession(); } }
-
Configure the Session of the current thread binding in the main configuration file
<!-- Configuring the current thread-bound Session --> <property name="hibernate.current_session_context_class">thread</property>
-
test
package com.itzhouq.hibernate.demo1; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.itzhouq.hibernate.utils.HibernateUtils; /* * Testing Session of Current Thread Binding */ public class Demo4 { @Test public void test() { Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); Customer customer = new Customer(); customer.setCust_name("Wang Xi"); session.save(customer); transaction.commit(); //session.close(); // No need to close } }
-
Note: The session of the bound thread does not need to be closed manually. Because the current thread automatically obtains the Session bound to the current thread, after the thread ends, it automatically closes the Sesson and does not need to close manually.
6. Other API s of HIbernate
6.1 Query
-
Query interface uses receiving HQL to query multiple objects
- HQL: Hibernate Query Language: HIbernate Query Language, which is similar to the syntax of SQL and its object-oriented query language.
- Code
package com.itzhouq.hibernate.demo1; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.itzhouq.hibernate.utils.HibernateUtils; /* * HIbernate Other API */ public class Demo5 { @Test // Query public void test() { Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); // Getting Query Interface through Session //Simple query //String hql = "from Customer"; //Conditional query //String hql = "from Customer wehre cust_name like ?"; //Paging query String hql = "from Customer"; Query query = session.createQuery(hql); //Setting conditions //query.setParameter(0,'King%'); //Setting Pagination query.setFirstResult(0); query.setMaxResults(3); List<Customer> list = query.list(); for (Customer customer : list) { System.out.println(customer); } transaction.commit(); } }
6.2 Criteria
-
Conditional Query: Query By Criteria
- A More Object-Oriented Query Method
-
Code
@Test // Criteria public void test2() { Session session = HibernateUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); //Obtaining Criteria objects through Session Criteria criteria = session.createCriteria(Customer.class); //List<Customer> list = criteria.list(); //Conditional query // Criteria add = criteria.add(Restrictions.like("cust_name", "king%"); // List<Customer> list = criteria.list(); //Paging query criteria.setFirstResult(0); criteria.setMaxResults(2); List<Customer> list = criteria.list(); for (Customer customer : list) { System.out.println(customer); } transaction.commit(); }
6.3 SQLQuery [Understanding]
- SQLQuery is used to receive SQL. Use SQL in particularly complex situations.