First, the primary key generation strategy
1. Type of primary key
Natural PRIMARY key: A field with a specific business meaning as the primary key eg: User's name, ID number
Surrogate PRIMARY key: A field that has no specific business meaning as the primary key Eg:id
Development inside the words usually with the proxy primary key
2. The generation strategy of the primary key
2.1 Overview
? Hibernate provides a number of primary key generation strategies for better data maintenance.
2.2 Primary key policy type
Increment: auto-grow, Applicable type: Short,int,long type primary key. Do not use in multi-process and cluster. Instead of automatic database growth, Hibernate's underlying growth strategy, select MAX (ID) from customer; Then +1 is the ID of the next record.
Assigned: Requires the user to manually enter the OID.
Identity: Automatic growth, with the automatic growth of the database. Applicable type: Short,int,long type primary key. Support for automatic growth of databases such as MySQL
Sequence: sequence, Applicable type: Short,int,long type primary key. A database that supports sequences such as: Oracle.
Native: Local policy, which uses identity or sequence based on the underlying database.
UUID: A random string that applies to the primary key of a string type.
Rule: If the primary key type is int short long with native
? If the primary key type is a string, use the UUID
Ii. rules for the writing of persistent classes1. Overview of Persistence Classes
? In Hibernate, the class used to describe the structure of a database table is called a persistent class.
? The Java class establishes a mapping relationship with a table in the database. This class is called a persistence class.
? Persistence class = Java class + HBM configuration file
2. Persistence class definition Specification
Follow the JavaBean definition specification
? Class is public
? Requires an argument-free constructor
? property is private and requires a public getter and setter method to access the property
You must use a property to describe the primary key of a database table
The type of the primary key attribute must be a reference type, and the serializable interface needs to be implemented
Iii. three states of persistent objects1. Overview
? The object created by the persisted class is the persisted object. Hibernate in order to manage persisted objects: The persisted object is divided into three states. Hibernate the underlying implementation process, the definition of the three states are mainly convenient for developers to invoke the session API.
? Differentiate three states:
? Transient state: No persistent identity OID, not included in the session management.
? Persistent State: There is persistent identity OID, which has been included in the management of the session.
? Managed (Free State) state: There is persistent identity OID, not included in the session management.
Java code:
/*** Distinguish three states: * Transient state: No persistent identity OID, not included in session management * Persistent State: There is persistent identity OID, and included session management * Managed state: There is persistent identity OID, but not included in session management*/@Test Public voidFun01 () {Session session=hibernateutils.opensession (); Transaction Transaction=session.begintransaction (); Transaction.begin (); User User=NewUser ();//instantaneous StateUser.setuname ("Zhang San"); User.setuage (18); Session.save (user); System.out.println (User.tostring ());//Persistent StateTransaction.commit (); Session.close (); System.out.println (User.tostring ());//Managed State}
2. Conversion of three states
2.1 Instantaneous state object
There is no persistent identity OID and is not included in the management of the Session object
2.2 Persistent State object
There is persistent identity OID, which has been included in the management of the Session object
Get: Get ()/load ()/find ().
State transitions:
? Persistent state---> Transient state: Session.delete (); (not recommended in hibernate)
? Persistent State---> Managed State: Close ()/clear ()/evict (Object obj);
2.3 Managed State Objects
There is persistent identity OID and is not included in the management of the Session object
Get: New object, set ID for object
State transitions:
? Managed state--instantaneous state: Sets the object's ID to null
? Managed State---> Persistent State: Update ()/saveorupdate ();
3. Persistent objects can automatically update the database
Persistent objects rely on caching to automatically update the database
1 @Test2 Public voidfun05 () {3Session session =hibernateutils.opensession ();4Transaction Transaction =session.begintransaction ();5 Transaction.begin ();6 //Persistent State Object7User user = Session.get (user.class, 1);8User.setuname ("John Doe");9 //session.update (user); Can not write because the current user is a persisted objectTen One transaction.commit (); A session.close (); -}
Iv. caching of Hibernate1. Caching Overview
? The cache is a piece of memory space.
? Reading data from a data source (database or file) into the cache and fetching it directly from the cache can improve the performance of the program!
? Function: Improve the performance of the program
cache category for 2.Hibernate
? First-level cache: the cache of Session objects, with their own non-unloaded. The life cycle of the first-level cache is consistent with the session.
? Secondary cache: Level Two caches can share data in multiple sessions. Generally not used, the enterprise usually uses Redis
3. First Level cache
? The implementation of the session interface contains a series of Java collections that form the session cache. As long as the Session instance does not have an end life cycle, the objects stored in its cache will not end the life cycle.
? When the Save () method of the session persists an object, the object is loaded into the cache, and in the future even if the object is no longer referenced in the program, the object remains in the lifecycle as long as the cache is not emptied. When an attempt is made to get (), load () The object, it is determined whether the object exists in the cache, or if it is returned, the database is not queried at this time. The database is no longer queried.
@org. Junit.test Public voidFun03 () {Session session=hibernateutils.opensession (); Transaction Transaction=session.begintransaction (); //Persistent State ObjectUser User1 = Session.get (user.class, 1);//send an SQL statement nowSystem.out.println (user1.tostring ()); User User2= Session.get (User.class, 1);//send an SQL statement nowSystem.out.println (user1 = = User2);//trueTransaction.commit (); Session.close (); }
Test results:
Hibernate:
Select
User0_.uid as uid1_0_0_,
User0_.uname as uname2_0_0_,
User0_.uage as Uage3_0_0_
From
User user0_
where
User0_.uid=?
User{uid=1, uname= ' John Doe ', uage=18}
True
4. The internal structure of the first level cache: (buffer, snapshot area)
v. Hibernate's Affairs1. The concept of a transaction
? A transaction is a logical set of operations that make up the individual execution units of a transaction, either successfully or all fail.
2. Characteristics of the transaction
? Atomicity: Transactions are inseparable.
? Eg: Zhang 31,000 Li 41,000; Zhang San to Lee four turn 100, either transfer success, or failure
? Consistency: The integrity of the data before and after the execution of a transaction remains consistent.
? Eg: Zhang 31,000 li 41,000 = 2000; Zhang San to Li four turn 100, succeeded Zhang 3,900 li 41,100 = 2000; Failed
? Isolation: During the execution of a transaction, it should not be interfered with by other transactions.
? Persistence: Once a transaction is committed, the data is persisted to the database.
? Eg: Zhang 31,000 li 41,000, give Li four turn 520;
3. Do not consider the problems related to isolation
Dirty Read : One transaction reads uncommitted data from another transaction.
non-repeatable read : One transaction read the update data that has been committed by another transaction, resulting in inconsistent results for multiple queries. Zhang 31,000; Li 41,000
Virtual Read : One transaction read the insert data that has been committed by another transaction, resulting in inconsistent structure of multiple queries.
4. Isolation Level
Isolation Level |
meaning |
read_uncommitted |
Allows you to read changed data that has not yet been submitted. may result in dirty, Phantom, non-repeatable reads |
read_committed |
Allows reading after a concurrent transaction has been committed. Prevents dirty reads, but Phantom reads and non-repeatable reads can still occur |
Repeatable_read |
Multiple reads of the same field are consistent unless the data is changed by the transaction itself. Can prevent dirty, non-repeatable reads, but Phantom reads can still occur. |
SERIALIZABLE |
Completely obey the isolation level of acid, ensuring that no dirty, phantom, non-repeatable reads occur. This is the slowest of all isolation levels, and it is typically done by fully locking the data tables involved in the transaction. |
In real development, the highest or lowest isolation level is not selected, read_committed (oracle default), Repeatable_read (mysql default)
5.Hibernate Configuring Isolation Levels
Hibernate by setting the isolation level in the Hibernate.cfg.xml configuration file:
<property name= "Hibernate.connection.isolation" >4</property>
Take value
? 1:read UNCOMMITTED isolation, read not submitted
? 2:read committed isolation, read submitted, fix dirty read.
? 4:repeatable read isolation, repeatable READ
? 8:serializable Isolation, serialization
6.hibernate Management of the session6.1 Bind the session to the current thread
? In development, things are usually managed at the business level, and the database is manipulated at the DAO level. That is, the business layer needs to connect (session) to open things, the DAO layer needs to connect (session) Operation database, how to ensure that these connections are the same?
? In the JDBC phase, we solved it in two ways:
? 1. Passing Parameters down
? 2. Bind to treadlocal inside.
? In Hibernate, the Session object is very simple to bind to the local thread, requiring only two steps:
-
in the Hibernate.cfg.xml file, add a property to open the session bound to the local thread
< Property name= "Hibernate.current_session_context_class" >thread</property>
Get session by Sessionfactory's Getcurrentsession () method
Sessionfactory. getcurrentsession ();
Note: The session obtained through the Getcurrentsession () method does not need to call the Close method to free resources. When things are committed or rolled back, resources are automatically freed.
the difference between 6.2 session acquisition method
When the Getcurrentsession () method is called, it determines whether the session is bound in the current thread.
? If bound, return directly to the bound session in the thread
? If there is no binding, first create a session, then the session is stored in the current thread, and then returned.
When the Opensession () method is called, only a new session is created and is not stored to the current thread.
The session obtained through the Getcurrentsession () method eliminates the need to call the Close method to free resources. Sessions obtained through the Opensession () method require manual resource release.
Getting Started with Hibernate (ii)