Session of the hibernate4.x

Source: Internet
Author: User

Hibernate Session Overview

The session interface is the primary interface that hibernate provides to the application to manipulate the database, which provides a basic way to save, update, delete, and load Java objects.

The session has a cache, and objects in the cache are called persisted objects, which correspond to related records in the database. The session is able to synchronize updates to the database by executing related SQL statements at some point in time, according to the changes in the objects in the cache, a process known as flush caching (flush).

Standing in the perspective of persistence, hibernate divides objects into 4 states: persistent state, temporary state, Free State, delete state. The specific method of the session allows the object to transition from one state to another.

Session 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-of-life cycle, and the cache is not cleaned, the objects stored in its cache do not end the life cycle.

Session caching reduces the frequency with which hibernate applications access the database.

Operation Session Cache:

Flush (): Session updates the database synchronously according to the properties of the objects in the cache

By default, the session refreshes the cache at the following point in time:
Explicitly calling the flush () method of the session
When the application calls transaction's commit () method, the method flushes the cache (flush) and then commits the transaction to the database
When an application executes a subquery (Hql,criteria) operation, if the properties of the persisted object in the cache have changed, the cache is flush () to ensure that the query results reflect the latest state of the persisted object
      

Exception to flush cache: If an object uses the native generator to generate an OID, an INSERT statement that inserts a modified entity into the database is immediately executed when the object is saved by invoking the Save () method of the session.
The difference between the commit () and flush () methods is that flush executes a series of SQL statements, but does not commit the transaction; The commit method calls the Flush method and then commits the transaction, meaning that committing the transaction means that the database operation is persisted.

Refresh (): The SELECT statement is forced to keep the state of the object in the session cache consistent with the corresponding record in the data table!
Clear (): Clean up the cache

Test class:

  

1  Packagecom.yl.hibernate.entities;2 3 Import Staticorg.junit.assert.*;4 5 Importjava.util.Date;6 7 Importorg.hibernate.Session;8 Importorg.hibernate.SessionFactory;9 Importorg.hibernate.Transaction;Ten Importorg.hibernate.cfg.Configuration; One ImportOrg.hibernate.service.ServiceRegistry; A ImportOrg.hibernate.service.ServiceRegistryBuilder; - ImportOrg.junit.After; - ImportOrg.junit.Before; the Importorg.junit.Test; -  -  Public classHibernatetest { -  +     Privatesessionfactory sessionfactory; -     PrivateSession session; +     PrivateTransaction Transaction; A      at @Before -      Public voidinit () { -Configuration Configuration =NewConfiguration (). Configure (); -Serviceregistry Serviceregistry = -                 NewServiceregistrybuilder (). Applysettings (Configuration.getproperties ()) - . Buildserviceregistry (); in  -Sessionfactory =configuration.buildsessionfactory (serviceregistry); to          +Session =sessionfactory.opensession (); -  theTransaction =session.begintransaction (); *     } $ @AfterPanax Notoginseng      Public voiddestory () { - transaction.commit (); the          + session.close (); A          the sessionfactory.close (); +     } -      $ @Test $      Public voidTestsessioncache () { -News News Session.get (News)class21st); - System.out.println (news); the Session.flush (); -News news2 = (news) Session.get (news).class21st);Wuyi System.out.println (NEWS2); the          -SYSTEM.OUT.PRINTLN (news = = NEWS2);//true Wu     } -  About     /** $ * Flush: Keeps the records in the database tables consistent with the state of the objects in the session cache. In order to remain consistent, the corresponding SQL statement may be sent.  - * 1. In transaction's commit () method: First call the session's Flush method, then commit the transaction - * The 2.flush () method may send an SQL statement, but the transaction will not be committed - * 3. Note: the flush () operation may also occur before the Session.flush () method is invoked for the commit transaction or display.  A * 1). Execute HQL or QBC query, flush operation first to get the record of the data table + * 2). If the record ID is generated by the underlying database using the self-increment, the INSERT statement is sent immediately when the Save method is called the * Because after the Save method, the ID of the object must be guaranteed to exist!  -      */ $ @Test the      Public voidTestFlush2 () { theNews news =NewNews ("Hibernate", "Oracle",NewDate ()); the Session.save (news); the     } -      in @Test the      Public voidTestflush () { theNews News Session.get (News)class21st); AboutNews.setauthor ("Bruce Eckel"); the          theNews news2 = (news) Session.createcriteria (news).class). Uniqueresult (); the System.out.println (NEWS2); +     } -      the     /**Bayi * Refresh (): The SELECT statement is forced to keep the state of the object in the session cache consistent with the corresponding record in the data table!  the      */ the @Test -      Public voidTestrefresh () { -News News Session.get (News)class21st); the System.out.println (news); the Session.refresh (news); the System.out.println (news); the     } -      the     /** the * Clear (): Clean up cache the      */94 @Test the      Public voidtestclear () { theNews news1 = (news) Session.get (news).class21st); the session.clear ();98News news2 = (news) Session.get (news).class21st); About     } -}

Session of the hibernate4.x

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.