1. Hibernate
- Is the middleware that connects Java applications and relational databases;
- The JDBC API is encapsulated and is responsible for the persistence of Java objects;
- In the three-tier software architecture, it is located in the persistence layer (the data Access layer), encapsulating all the data access details so that the business logic layer can focus on implementing the business logic;
- It is an ORM mapping tool that can establish a mapping between an object-oriented domain model and a relational data model.
- is a durable layer solution for lightweight Java EE applications.
2, the role of Hibernate framework:
- Hibernate is mainly used to implement the mapping between the Java object and the table of data, in addition to provide data query and data acquisition methods;
- Hibernate can drastically reduce the time it takes to manually write SQL statements and JDBC code during development;
- Hibernate can completely isolate the database and decouple the dependencies between the project and the database;
- Hibernate's goal is to streamline the developer's usual data persistence-related programming tasks, freeing up 95% of them.
3, PO (Persistent object): Persistent object, is a very important medium in all ORM frameworks. The purpose of the PO is to complete the persistence operation, that is, through the object can perform additions and deletions of the data to the operation, in an object-oriented way to manipulate the database. Po=pojo+xml the map file.
4. Hibernate operation steps:
- Writing Pojo;
- Write the Pojo mapping file (Pojo class name. hbm.xml);
- Configuration mapping file (hibernate.cfg.xml);
- Get configuration;
- Get sessionfactory;
- Get session;
- Open a transaction;
- Manipulate the database in an object-oriented manner;
- Close the transaction, close the session, and close the sessionfactory.
5. Hibernate's Persistence class rules:
- Provides a parameterless constructor;
- Provides an identity property that identifies a primary key field that typically maps a database table. If you use a database table federated primary key, you need a custom class that has the properties of the Federated primary key type;
- Provides a Set/get method for each property of a persisted class;
- The persistence class must be a non-final class;
6. Hibernate Persistent Object state:
- Transient: The object is created by the new operator and the object that has not yet been associated with the session is considered transient. Transient objects are not persisted to the database and are not given persistent identities.
- Persistent state: The persisted instance has a corresponding record in the database and has a persistent identity. The persisted object must be associated with the specified session. Hibernate detects changes to the persisted state object, writes the object data back to the database when the current operation completes, and the developer does not have to manually update the database;
- Off-state: an instance is once in a persistent state, but as the session associated with it is closed, the object becomes off-state. The reference to the off-pipe object is still valid and the object can continue to be modified. If you re-associate a riser object with a session, the object will be converted to a persisted state, and changes to the de-tube can be written to the database.
New allows you to create a transient object,
Transient-"Persistent state: Save (), Saveorupdate (), Persist ()
Persistent state--"off-pipe Status: Evict (), close (), clear ()
Off-pipe-" persistent":up date (), Saveorupdate (), Lock ()
Persistence-"transient": Delete ()
Get persisted state object: Get (), load (), find ()
7, session of the method
Save (Obect obj,object PK): Save the Transient object to the database and specify the primary key value;
Persist (Object obj,object PK);
Save when you save a persisted object, it returns the identity property of the persisted object (the primary key value of the corresponding record), and the persist method does not return a value.
Load (): Used to load a persisted instance where a new record is loaded from the database table based on the primary key, and load throws an exception if there is no matching database record, and if lazy loading is specified in the class-map file, the Load method returns an uninitialized proxy object;
Get (): Similar to the Load () method, returns null if there is no matching database record, and does not return a proxy object;
Flash (): Refreshes the persisted object associated with the session, keeping it in sync with the database;
The load method and the persisted instance loaded by the Get method are modified to be automatically saved to the database before the session's Flush method, and no further processing is required.
Updateorsave (Object obj): Used to not know whether the object has been persisted, the method will automatically judge the object, if persisted, call Update, otherwise call save;
Merge (Object obj): You can save the program's modifications to the riser object to the database, but the most important difference from the Update method is that the merge method does not persist the object, that is, the Execute Merge method simply saves the object's properties to the database, and the object itself is still in the off-pipe state , will not be linked to the session;
Lock (Object Obj,lockmode): Used to re-persist an object in the de-state, but the riser object must not have been modified. The lock method can be used with multiple lockmode modes.
Delete (Object obj): Used to change a persisted instance from a persisted state to a transient, while the data record corresponding to the persisted instance is also deleted;
Structure of the mapping file:
8. Hibernate mapping File
Map PRIMARY key: During project development, it is recommended that you do not use physical primary keys that are meaningful, but that you should use logical primary keys that do not have any meaning.
Map Normal Properties:
- Type: Specifies the data type of the normal attribute, you can specify the Hibernate base type name (such as INTEGER,STRING,CHARACTER,DATE,TIMESTAMP,FLOAT,BINARY,OBJECT,BLOB, etc.), You can also specify Java basic types (such as INT,FLOAT,CHAR,STRING,DATE,INTEGER,CLOB, etc.);
- Index: Specifies the indexed name of a string;
- Length: Specifies the field length of the data column to which the attribute is mapped;
- Precision: Specifies the number of digits of the valid digits of the data column to which the attribute is mapped;
- Scale: Specifies the number of decimal digits of the data column to which the attribute is mapped;
9. Map Collection Properties:
One is a list, set or array of sets of properties, one is a map structure;
- Hibernate requires that the persisted set value field be declared as an interface;
- Collection class instances have the behavior of value types, which are automatically persisted when persisted objects are saved, and records for those collection properties are automatically deleted when the persisted object is deleted, or if the collection element is passed from one persisted object to another. The records corresponding to the collection elements are also transferred from one table to another;
- Two persisted objects cannot share a reference to a collection element;
Bag element Mapping:
The <bag> element can map the list collection properties, or it can map the set collection properties, or even the collection collection properties. Regardless of the collection property, the <bag> element is mapped to an unordered collection, and the corresponding table for the collection property has no primary key.
Mapping Map Collection Properties
Hibernate maps the properties of a list collection using the <map> element, and when configuring <map> elements, you also need to map the foreign key columns with <key> child elements, and the map collection properties also need to map the map key.
Hibernate takes the outside key column and key column as the Federated primary key.
order-by= "Field desc" query sequentially
Lazy= "False" can be set for a single collection element
The properties of ordered set have good performance in the operation of increment, delete, change and check database.
The records in the Collection property table are completely "subordinate" to the main table, and when the records of the primary table are deleted, the data from the collection's property table "subordinate" and the record will be deleted. Hibernate cannot directly load and query records in the collection's property sheet, only the primary table is loaded, and the records for the collection properties are obtained from the main table.
Map Component Properties:
A component attribute is a property of a persisted class, not a base data type, but a composite type that, during persistence, is only treated as a value type and not as a reference to another persisted entity.
Hibernate uses the <component> element map component properties, and each <component> element maps a component property. In addition to this, you need to use the <parent> child element mapping component class to specify a reference to its container entity.
If the component's properties are basic type, use <property> child element mapping;
If the component's properties are component types, use the <nested-composite-element> child elements to map these nested component properties;
If the properties of the component refer to other persisted entities, the <many-to-one> child element mapping is used;
Federated primary Key mappings:
Hibernate allows a multi-column mapping of persisted classes to be called a federated primary key directly, but requires the following two requirements:
Implementation of serializable serialization interface;
Overrides the Equals () method and the Hashcode () method according to the properties mapped by the Federated Primary key column.
Commonly used hibernate annotation Tags:
@Entity declares that the class is a persistent class;
@Table (name= "Promotion_info")
@Id, @GeneratedValue, @Version, @Transient, @Enumerated, @OrderBy, @Formula
Hibernate Association Mappings
Association relationship: Objects in the objective world are often interrelated, and relational relationships are the most important content of object-oriented analysis and object-oriented design, and hibernate can fully understand this association and make associative mappings. Association relationships generally fall into two categories: one-way and two-way associations.
Bidirectional many-to-one association, the habit by a number of parties to control, that is, inverse= "false", will be set to a few inverse= "true".
Bidirectional many-to-many associations can only use join tables to establish association relationships between two entities (many-to-many conversions to two one-to-many relationships).
In actual project development, the use of composite primary keys is not recommended, and it is recommended to adopt a logical primary key without physical meaning, which will not only increase the difficulty of database modeling, but also increase the maintenance cost of related relationships.
Component properties default initiates cascading operations, and associated mappings do not initiate cascading operations by default.
There are three strategies for hibernate inheritance mapping:
<subclass>,<joined-subclass>,<union-subclass> under this mapping strategy, you do not need to use either the distinguished column or the <key> element to map the common primary key. Note: Using the Union-subclass mapping policy, you cannot use the identity primary key to generate a policy or use native.
HQL is an object-oriented query language. The operands of SQL are data tables, columns, and records, while the HQL objects are classes, instances, and properties.
HQL Query the basic steps:
- Gets the session object;
- Write HQL statements;
- Using the HQL statement as the argument, call the session's CreateQuery method to create the query object;
- Call the list method of the query object to return the query result listing (the persisted object collection);
FROM clause:
The From is the simplest HQL statement, followed by the class name of the persisted class;
The HQL statement itself is case-insensitive, but the package name, class name, instance name, and attribute names used in the HQL statement are case-sensitive.
SELECT clause:
Select is used to choose an instance of a persisted class or a property specified by a persisted class;
PLACEHOLDER:
Use the English question mark (?) with a colon + name (: name)
Query has two methods to support the paging function: setfirstresult (int firstresult), setmaxresults (int maxResults)
Linked table query: Hibernate uses association mappings to process connections between underlying data tables.
HQL supports two types of associative connections: Implicit association connections and display associated connections.
- The implicit connection is converted to a cross-join of SQL (Cartesian product), which shows that the connection will be converted to SQL's multi-table connection (inner join, left OUTER JOIN, etc.);
- An implicit join query returns a collection of multiple queried entities, and the result that the connection query returns is also a collection, but the collection element is an array of persisted objects being queried, all of which are associated persisted objects;
Fetch keyword:
For persistent classes with collection properties, hibernate defaults to lazy load policy, does not load collection properties, the workaround has two, 1: configuration specifies lazy= "false" Shutdown deferred load 2: In the HQL statement by adding the FETCH keyword to grab the persisted class collection properties;
Named query: Getnamedquery (""), which is configured in the XML of the corresponding class.
Conditional query: Use the session to create a criteria object, through the object. Add (restrictios. Conditions), and then Criteria.list () to get a collection of query results.
SQL query: Used to port old artifacts, such as JDBC-based applications, to hibernate applications, and to HQL features of some databases that cannot be supported.
For a new Hibernate application, it is recommended that you do not use SQL queries directly, and you should use HQL more.
Filter: Hibernate does not start the filter by default.
Caching mechanism:
Session level cache (default on): Flush is called when session is closed, update data in cache to database, reduce database operation, improve performance
Sessionfactory level two cache (default off): Is global, all sessions of the application share a level two cache, when the program opens a two-level cache, the session needs to obtain data, it takes precedence from the two-level cache.
<property name= "Hibernate.cache.use_second_level_cache" >true</property>
Hibernaete pessimistic lock, optimistic locking mechanism:
Database Concurrency: Multiple transactions can access data in the database at the same time. When multiple transactions execute concurrently in the database, the data consistency can be compromised, causing problems with the data.
Pessimistic lock: That is, a transaction locks the data during the update process, no other transactions can be read or modified, and must be modified to access the data (similar to the Java thread synchronization mechanism);
Features: exclusivity, usually dependent on the database mechanism;
Applicable scenario: generally suitable for short transaction processing;
Use: Hibernate uses the Load () method to set the pessimistic lock if a pessimistic lock is required, usually with the database's for UPDATE statement.
Note: If a pessimistic lock is used, then the delay load is not valid.
Optimistic Lock: Optimistic lock is not a locking mechanism, but a conflict detection mechanism;
Features: Concurrency is good, transaction modification data, other transactions can still modify data;
Use: Commonly used is the version method (that is, each data table has a version of the field, version number +1, a transaction update, and then +1, when the transaction Discovery database current version number and data read the version number is inconsistent (or less than the database current version number) can not update data).
Turn on optimistic Lock: Configure the corresponding item in the mapping file, optimistic-lock= "version"
Note: The version field that is added is maintained by hibernate.
Hibernate Performance Optimizations:
Batch: Manually invoke the Flush () and clear () methods of the session, write the first-level cache to the database, and then empty. Also note that you need to turn off the sessionfactory level two cache.
Lazy loading: It can be divided into three types: delayed loading of objects, delay loading of attributes in objects, and set delay loading;
Hibernate uses the proxy mechanism to implement delay loading.
Java EE hibernate primary concept