1. Persisting class Authoring rules
Hibernate is a persistence-level ORM mapping framework that focuses on the persistence of data.
Persistence: The so-called persistence is to say that the in-memory data is persisted to the relational database.
Persistence class: The so-called persistence class refers to a Java class that establishes a mapping relationship with a database table, and this class is called a persisted class. In fact, you can simply understand that it is a Java class that establishes a relationship with a database table through a mapping file. The rules for writing persistent classes are as follows:
1. The persistence class provides parameterless constructs: because of the need to use reflection to generate an instance of the class at the bottom of hibernate;
2. Member variables are private and provide a common Get/set method access. Attributes are required, because hibernate is encapsulated in the underlying data;
3. Properties in a persisted class should use the wrapper type as much as possible: because the wrapper class and the base data type have different default values, the wrapper class has a clearer type semantic description, and the base data type is not easy to describe. For example: If the table has a list of employee salaries, if you use a double type, if the employee's salary is forgotten to enter the system, the system will be the default value of 0 to the database, if the employee's salary is deducted, will also be deposited in the system 0. Then this 0 has multiple meanings, and if the use of the packaging type will avoid the above situation, if the use of double type, forget to enter the wages will be deposited null, and this employee pay is deducted, will be deposited 0, will not produce ambiguity.
4. The persistence class needs to provide an OID. Corresponds to the primary key column in the database; This unique identity oid is used in hibernate to differentiate whether the same persisted class instance is in memory. In Java, whether the same object is distinguished by address, whether the same record is distinguished by a primary key in a table in a relational database. Hibernate is then distinguished by this OID. Hibernate is a persistent object that does not allow the same two OIDs to appear in memory.
5. Do not use the final modifier class: Because Hibernate has a mechanism of lazy loading, this mechanism will produce proxy objects, Hibernate generated proxy object using the bytecode enhancement technology, in fact, produced a subclass of the current class object implementation. If the final adornment persistence class is used, then the subclass cannot be generated, so the proxy object is not generated, and Hibernate's deferred-loading strategy (which is an optimization method) is invalidated. (Hibernate uses the Cglib proxy to generate proxy objects.) The proxy object is inherited by the proxy object. If it is final decorated. The agent cannot be generated.
Persisted classes we can already write normally, but in a persisted class we need to have a unique identity OID with the table's primary key to establish a mapping relationship. And the primary key generally we will not let the customer manually input, generally we are generated by the program primary key. Hibernate also provides a way to generate the corresponding primary key, so let's look at Hibernate's primary key generation strategy.
2. Hibernate primary key generation policy
Type of primary key: Before explaining Hibernate's primary key generation strategy, first understand the two concepts, the natural primary key and the proxy primary key, as follows:
- Natural PRIMARY key: In the business column of a table, there is a business column that conforms to: a feature that must have, and not be duplicated, that column can be used as a primary key, called a natural primary key, such as in the Customer table, if the Name field is the primary key, the precondition is that each customer's name is not allowed to be null, The customer name is not allowed, and customer names are not allowed to be modified. While this is possible, it does not meet changing business requirements, and once the business needs that allow the customer's name are met, the data model must be modified to redefine the table's primary key, which makes maintenance of the database more difficult.
- Surrogate PRIMARY Key: In the Business column of the table, there is no business column that conforms to: when there must be no duplicate characteristics, create a column with no business meaning as the primary key, and a field that does not have business meaning as the primary key, which is called the surrogate primary key. This field is generally named ID, usually an integer type, because the integer type saves more database space than the string type. In the above example, it is obvious that a more reasonable way is to use the surrogate primary key.
Hibernate provides several built-in primary key generation strategies, with the name and description of the common primary key generation policy as follows:
- Natural PRIMARY Key Type
- Assigned: Natural primary key generation strategy. Hibernate does not manage primary key values. Input by the developer themselves; the Java program is responsible for generating identifiers, and if you do not specify the Generate attribute of the ID element, the policy is generated by default using that primary key. Applies to natural primary keys.
- Proxy primary Key
- The primary key generation policy in Sequence:oracle. Hibernate generates identifiers based on the underlying database sequence. The condition is that the database supports the sequence and is applicable to the proxy primary key.
- Increment (understanding): Primary key self-increment. It is maintained by hibernate. The maximum ID value in the table is queried before each insert. +1 as the new primary key value; for long, short, or int types, Hibernate automatically generates a unique identifier incrementally, Each increment is 1. It can only be used if no other process is inserting data into the same table, and cannot be used in a clustered environment. Applies to the proxy primary key.
- Identity: Generates identifiers using the primary key provided by the underlying database, if the database supports autogrow data types. The generator can be used in DB2, MySQL, MS SQL Server, Sybase, and Hypersonicsql databases, which require that the primary key be defined as a self-growing type in the database, and for the proxy primary key.
- Hilo (Understanding): high-low-level algorithm. The primary key is self-increment. Maintained by hibernate. Not used during development.
- Native:hilo+sequence+identity automatic three-choice strategy. Based on the ability of the underlying database to automatically generate identifiers, one of the three generators for identity, sequence, and Hilo is available for cross-database platform development. Applies to the proxy primary key.
- UUID: Generates a random string as the primary key. The primary key type must be of type string. Hibernate uses a 128-bit UUID algorithm to generate identifiers. The algorithm can generate a unique string identifier in a network environment whose UUID is encoded as a 32-bit hexadecimal string. This strategy is not popular because the primary key of a string type consumes more database space than the primary key of an integer type, and is appropriate for the proxy primary key.
3. Hibernate persistent objects in three states
After understanding the primary key generation strategy, we can further understand the persistence class. Hibernate to better manage persistence classes, the persistence class is divided into three states: transient, persistent, and managed, and an instance of a persisted class may be in one of three different states.
There is no ID, not in the session cache; Transient states are called temporary states or free states, instances of transient states are objects created by the new command, open memory space, there is no persistent identity oid (equivalent to the primary key value), has not been associated with hibernate session, There is no record in the database, and the JVM is recycled after the reference is lost. Instantaneous state objects are isolated in memory and have no association with the data in the database, only a carrier of information carrying.
There is an ID in the session cache; Persistent Identity OID is added to the session cache, and the associated session is not closed, there are corresponding records in the database, each record only corresponds to the only persisted object, it should be noted that A persisted object becomes persisted until the transaction has not been committed.
There is an ID, not in the session cache; a managed state is also called an off-line or Free State, which becomes a managed state when an instance of a persisted state is closed to the session. The managed-state object has a persistent identity OID and is still associated with the data in the database, but hibernate cannot detect when the managed state object changes because the current session is lost.
We have already introduced the three states of persistent objects, in fact, we mainly to study the persistence of the object is enough, the persistent object has a very important feature: Persistent objects can automatically update the database.
Instance:
1. Writing test Code
1 @Test2 Public voidDemo7 () {3 //Open Transaction4Transaction tx =session.begintransaction ();5 //getting persisted objects6Customer customer = Session.get (customer.class, 1l);7Customer.setcust_name ("Nakelulu");8 //do not call Session.update (customer);9 tx.commit ();Ten session.close (); One}
Demo7
Hibernate automatically calls the Update method.
4. Hibernate's first-level cache
- Hibernate caching principle
Caching is a very common concept in the domain of computers. It is between an application and a persistent data storage source, such as a file on a hard disk or a database, to reduce the frequency with which the application directly reads and writes to the persistent data storage source, thereby improving the performance of the application. The data in the cache is a copy of the data in the data storage source. The physical media that is cached is usually memory.
Hibernate caches are classified as primary and level two caches, and Hibernate's level two cache is located in the persistence layer, which stores backups of database data. Where the first level cache is Hibernate's built-in cache and cannot be uninstalled.
Hibernate's first-level cache refers to the session cache, the session cache is a piece of memory space, used to store the mutually managed Java objects, when using Hibernate query object, The OID value of the object property is first used to find in the hibernate cache, and if a match OID is found, the object is fetched directly from the primary cache, no longer queried, and if no object of the same OID value is found, the database is searched for the corresponding data.
When you query from the database for the data that you want, the data information is also placed in the first-level cache. Hibernate's first-level caching is about reducing the number of accesses to the database.
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. Therefore, the first-level cache is also known as the session basic cache.
Hibernate's first-level cache has the following features:
1. When the application calls save (), update (), and Saveorupdate () of the session interface, Hibernate automatically joins the corresponding object information queried from the database to the first level cache if there are no corresponding objects in the session cache.
2. When the load (), get () method of the session interface is called, and the list (), iterator () method of the query interface, the object is determined to exist in the cache, there is a return, the database is not queried, if there are no objects to query in the cache, The corresponding object is queried in the database and added to the first-level cache.
3. When the close () method of the session is called, the session cache is emptied.
Prove the existence of a first-level cache:
1 @Test2 Public voidDemo8 () {3Transaction tx =session.begintransaction ();4Customer Customer1 = Session.get (customer.class, 1l);//Hibernate Query Database5 System.out.println (customer1);6Customer Customer2 = Session.get (customer.class, 1l);//do not query the database7System.out.println (CUSTOMER1==CUSTOMER2);//true8 System.out.println (customer2);9 tx.commit ();Ten session.close (); One}
Demo8
- The internal structure of the first-level cache (snapshot area)
Hibernate puts data into the first-level cache while copying a copy of the data into the hibernate snapshot, while the commit () method commits the transaction and cleans up the session's first-level cache, using the OID to determine whether the objects in the primary cache and the objects in the snapshot are consistent , if a property in two objects changes, the UPDATE statement is executed, the cached content is synchronized to the database, and the snapshot is updated: if it is consistent, the UPDATE statement is not executed. The purpose of hibernate snapshots is to ensure that the data in the first-level cache is consistent with the data in the database.
3.1 Hibernate persistence class and first level cache