Hibernate Learning (2), hibernate Learning

Source: Internet
Author: User

Hibernate Learning (2), hibernate Learning
1. Hibernate core API1 and Configuration object (Configuration)

The configuration object is the first Hibernate object you create in any Hibernate application, and is often created only during application initialization. It represents a configuration or attribute file required by Hibernate. The configuration object provides two basic components.

  • Database Connection: One or more configuration files supported by Hibernate. These files areHibernate. propertiesAndHibernate. cfg. xml.
  • Class ing settings: This component creates a connection between Java classes and database tables.
2. SessionFactory object

The configuration object is used to create a SessionFactory object. The provided configuration file is used to configure Hibernate for the application in sequence, and a session object can be instantiated.

SessionFactory isThread security objectAnd used by all threads of the application.

SessionFactory is a heavyweight Object, so it is usually created at application startup and then retained for future use. Each database requires a SessionFactory object to use a separate configuration file. Therefore, if you use multiple databases, you need to create multiple SessionFactory objects.

Main functions:Creates a Session object.

Concept:The SessionFactory object stores the current database configuration information, all ing relationships, and predefined SQL statements. SessionFactory is also responsible for maintaining the Hibernate second-level cache and querying the cache.

Note:

1. The creation of SessionFactory objects has a large overhead because SessionFactory usesThread SecurityThe actual SessionFactory object can beShare as much as possible, In most cases,An application can share a SessionFactory instance for a database..

2. A request: A Session object (including a connection object, a transaction object, and a level-1 cache ).

Important methods:

1. openSession. This method indicates opening a new Session.

  • New Connection
  • New transactions
  • New level-1 Cache

2. getCurrentSession: Get the session in the current context

  • If a session exists in the current context, the session is used;
  • If no session exists in the current context, use opensession to create a new session.
  • To use getCurrentSessoin, you must configure thread <property name = "current_session_context_class"> thread </property> In hibernate. cfg. xml.
  • The session obtained by getCurrentSession is bound to the transaction;
  • Whether it is DML (data operation language) or DQL (Data Query Language), transactions must be enabled
  • When a transaction is committed, the session is closed.

Therefore, you can extract the SessionFactory object to a tool class and use the static Singleton mode:

1 package com. hibernate. util; 2 3 import org. hibernate. session; 4 import org. hibernate. sessionFactory; 5 import org. hibernate. cfg. configuration; 6 7/** 8 * @ author zt1994 2018/3/7 9 */10 public class HibernateUtil {11 private static SessionFactory sessionFactory; 12 13 static {14 try {15/1. read and parse the Configuration file 16 configuration Configuration = new Configuration (); 17 // 2. load the configuration file. If you do not configure to load the default configuration file hibernate. cfg. xml18 configuration. configure ("hibernate. cfg. xml "); 19 // 3. generate session factory 20 sessionFactory = configuration. buildSessionFactory (); 21} catch (Exception e) {22 e. printStackTrace (); 23} 24} 25 26 public static Session getSession () {27 // 4. get session28 return sessionFactory. openSession (); 29} 30}
3. Session Object

A session is used to obtain the physical connection to the database. The Session object is lightweight and is designed to interact with the database each time it is instantiated. The most widely used persistence manager provides persistence-related operations. Add, delete, modify, and query.

Session objects should not be enabled for a long time. Because they are not thread-safe, they should be created and destroyed as needed. Because Session objects are lightweight, creating and destroying do not consume too much resources.

Therefore, a Session object can only be used by one thread. Avoid sharing multiple threads.

Main functions:The main function of Session is to create, read, and delete instances mapped to object classes.

1. Level 1 Cache

The Session contains a cache called a level-1 cache. Stores the objects loaded by the current work unit.

Test level 1 cache:

1/** 2 * Test cache 3 */4 @ Test 5 public void testCache () {6 // 1. obtain session 7 Session session = HibernateUtil. getSession (); 8 Transaction transaction = null; 9 try {10 // 2. enable transaction 11 transaction = session. getTransaction (); 12 transaction. begin (); 13 // 3. operation CRUD14 Product product1 = (Product) session. get (Product. class, 70); 15 System. out. println (product1.hashCode (); 16 Product product2 = (Product) session. get (Pr Oduct. class, 70); 17 System. out. println (product2.hashCode (); 18 Product product3 = (Product) session. get (Product. class, 71); 19 System. out. println (product3.hashCode (); 20 transaction. commit (); 21} catch (Exception e) {22 if (transaction! = Null) transaction. rollback (); // roll back 23 e. printStackTrace (); 24} finally {25 // 4. close resource 26 session. close (); 27} 28}

Output:

Conclusion:Obtain from the first-level cache. If no result is obtained, issue the SQL statement and put it into the first-level cache.
First-level cache hit: Only one SQL statement is sent
First-level cache hit condition: whether the OID of the same session is the same
Structure of the primary cache:
OID: Object ID, which is defined in hibernate
The Operation's Persistent Object is fully qualified class name + "#" + database primary key value
Com. hibernate. day01.model. LoginUser #1
Stored in Map <String, Object> cacheMap

2. Hibernate status:

Transient. This object becomes an instantaneous object.

Persistent: the relationship between the hosting status and session has been persisted and added to the session level-1 cache. The object in this state is a persistent object.

Detached: the unmanaged status is persistent but not in the session. The object in this status is a free object.

Removed: only when the session is called is in the status that appears from jpa. the delete (domain object) method object has an associated ID and is scheduled to be deleted under Session management (when a transaction is committed ).

 

3. Change objects in the persistent state to the Free State.

Session. close (): clears and closes the first-level cache.

Session. clear (): clears the first-level cache.

Session. evict (object Persistent object): clears the Persistent object specified in the first-level cache.

4. Transaction object

A transaction represents a unit that works with the database, and most RDBMS supports the transaction function. In Hibernate, transactions are processed by the underlying transaction manager and transactions (from JDBC or JTA. This is a selective object. Hibernate applications may not choose to use this interface, but manage transactions in their own application code.

5. Query object

Query objects use SQL or Hibernate Query language (HQL) strings to retrieve data in the database and create objects. A query instance is used to link query parameters, limit the number of results returned by the query, and finally execute the query.

6. Criteria object

The Criteria object is used to create and execute rule-oriented query objects to retrieve objects.

Ii. Dirty data update

A persistent State object is in the transaction management. Once the original data (non-primary key) is changed (dirty data occurs), the transaction automatically sends an update to modify it when it is committed.

1/** 2 * test dirty read 3 * cause: 4*1. The object obtained through Session is a persistent object, which will be placed in the first-level cache; 5 * Hibernate will prepare a snapshot (Backup) for the current object; 6*2. when the transaction is committed, the snapshot will be compared with the current object. 7 * If the snapshot is the same, no modification is required, and no SQL statement is generated. 8 * if it is different, Hibernate considers the current data as dirty data and synchronizes it to the database (where an SQL statement occurs) 9 */10 @ Test11 public void test1 () {12 // 1. obtain session13 Session session = HibernateUtil. getSession (); 14 Transaction transaction = null; 15 try {16 // 2. start transaction 17 transaction = session. getTransaction (); 18 Transaction. begin (); 19 // 3. operation CRUD20 Product product = (Product) session. get (Product. class, 70); 21 product. setName ("Dirty read test"); 22 // 4. commit transaction 23 transaction. commit (); 24} catch (Exception e) {25 if (transaction! = Null) transaction. rollback (); // roll back 26 e. printStackTrace (); 27} finally {28 // 5. disable resource 29 session. close (); 30} 31}

Output:

The output shows that the update method is automatically called for database synchronization.

Iii. Delayed Loading

  Delayed loading (lazy loading ):A non-primary key attribute is required to issue an SQL statement. Obtaining a non-primary key attribute value improves performance. However, if the session is closed in advance, a delayed initialization exception occurs.

Note:
1. If no primary key exists, an error is returned.

2. Close the session in advance and report an error

1/** 2 * Test delayed loading 3 */4 @ Test 5 public void testLoad () {6 // 1. obtain session 7 Session session = HibernateUtil. getSession (); 8 Transaction transaction = null; 9 try {10 // 2. enable transaction 11 transaction = session. getTransaction (); 12 transaction. begin (); 13 // 3. operation CRUD14 Product product = (Product) session. load (Product. class, 1); // only generates an SQL statement and does not send 15 systems. out. println (product. getName (); // The SQL statement 16 is sent here // 4. commit transaction 17 tran Saction. commit (); 18} catch (Exception e) {19 if (transaction! = Null) transaction. rollback (); // roll back 20 e. printStackTrace (); 21} finally {22 // 5. close resource 23 session. close (); 24} 25}

Differences between get and load:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.