hibernate04--conversion between three states

Source: Internet
Author: User

public class Studenttest {Session session=null;    Transaction Transaction=null; Execute the Before @Before public void before () {/** * 01) before executing the test method. Reads the core configuration file under the SRC root directory!         The bottom of the prescribed location! * When instantiating a Configuration object, go to the SRC root by Configure () * To find the Hibernate.cfg.xml file */configuration Config        Uration=new Configuration (). Configure ();        02. Create Sessionfactory Sessionfactory sessionfactory = Configuration.buildsessionfactory ();        03. Open Session Session = Sessionfactory.opensession ();    04. Open Transaction transaction= session.begintransaction ();         }//After executing the test method @After public void after () {//07. COMMIT TRANSACTION SQL statement overall execution!         Transaction.commit ();         08. Close Session Session.close (); Sessionfactory.close ();     Verify the three states of the Create-drop}/** * Hibernate object in HBM2DDL! * 01. Transient status (temporary status/Free State) * We created an entity object from the New keyword!     And hibernate don't have a half-dime relationship! * * 02. Persistent status    * object is being managed by the session, the database has the data corresponding to the object!  * If the object is persistent state!     Then the modification operation does not need to use the other method (update) * At commit time, will execute flush (), * flush () will be cache cleanup!     * Dirty check will be done when the cache is cleaned!     * If the object's properties and previous object properties are inconsistent!     * Then the current object is a dirty object!     * The dirty objects will be synced to the database! * * 03. Free State (off-state) * Once managed by the session!     The difference between the instantaneous state is whether the OID (primary key identifier) exists!  * */@Test public void testSave1 () {//Create an Object Student stu=new Student (100, 50, "old White");   Instantaneous state session.save (STU);          Persistent state stu.setname ("Old Vain");          /** changing the properties of an object this time the Stu is that the dirty object does not need to execute update () commit when it will produce two SQL statements!   01.insert 02.update */@Test public void TestSave02 () {//Create an object Student  Stu=new Student (666, 50, "old White");  Instantaneous state stu.setname ("Old Vain");   Instantaneous state session.save (STU);    The persistence state starts here to be managed by the session!  } @Test public void TestSave03 () {//Create an Object Student stu=new Student (555, 50, "old White");  Instantaneous state      Stu.setname ("Old Vain");   Instantaneous state session.save (STU);        The persistence state starts here to be managed by the session!          Stu.setname ("Old Vain 1");          Stu.setname ("Old Vain 2");          Stu.setname ("Old Vain 3");          /** * or two SQL statements *commit will produce two SQL statements! 01.insert 02.update * * */** * Test method Premise Environment three cases * 01.stu objects do not have corresponding data in the database * 02.     The Stu object has the corresponding data in the database, but we have not modified the property * 03.stu object has corresponding data in the database, we have modified the properties * results are consistent!  * Generate UPDATE statement based on ID */@Test public void Testupdate () {//Create an Object Student stu=new Student (1, 50,  "Old White");    Instantaneous state session.update (STU); }/** * Prerequisite environment for test method * Stu object does not have corresponding data in database * Result: * 01. Generate SELECT * 02 based on ID. There are no corresponding numbers in the discovery database The resulting insert */@Test public void Testsaveorupdate () {//Creates an object Student stu=new Student (1, 50,  "Old White");    Instantaneous state session.saveorupdate (STU); }/** * Prerequisite environment for test methods * 01.stu objects have corresponding data in the database * 02. No change.Variable Stu the property value of the object * Results: * Generate a SELECT statement based on ID */@Test public void TestSaveOrUpdate2 () {//Create an Object  Student stu=new Student (1, 50, "old White");    Instantaneous state session.saveorupdate (STU); }/** * Prerequisite environment for test methods * 01.stu objects have corresponding data in the database * 02. Changed the property value of the Stu Object * Results generated: * 01. Generate SELEC based on ID  T * 02. Perform UPDATE */@Test public void TestSaveOrUpdate3 () {//Create an object because the object's properties have been modified Student  Stu=new Student (1, 50, "old White");        Instantaneous state stu.setname ("Old Vain");    Session.saveorupdate (Stu); }    }





Package Cn.bdqn.test;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;import Org.junit.after;import Org.junit.Before;    Import Org.junit.test;import Cn.bdqn.bean.student;public class Studenttest {Session session=null;    Transaction Transaction=null; Execute the Before @Before public void before () {/** * 01) before executing the test method. Reads the core configuration file under the SRC root directory!         The bottom of the prescribed location! * When instantiating a Configuration object, go to the SRC root by Configure () * To find the Hibernate.cfg.xml file */configuration Config        Uration=new Configuration (). Configure ();        02. Create Sessionfactory Sessionfactory sessionfactory = Configuration.buildsessionfactory ();        03. Open Session Session = Sessionfactory.opensession ();    04. Open Transaction transaction= session.begintransaction ();         }//After executing the test method @After public void after () {//07. COMMIT TRANSACTION SQL statement overall execution! Transaction.cOmmit ();         08. Close Session Session.close (); Sessionfactory.close ();     Verify the three states of the Create-drop}/** * Hibernate object in HBM2DDL! * 01. Transient status (temporary status/Free State) * We created an entity object from the New keyword!     And hibernate don't have a half-dime relationship!     * * 02. Persistent Status * object is being managed by the session, the database has the data corresponding to the object!  * If the object is persistent state!     Then the modification operation does not need to use the other method (update) * At commit time, will execute flush (), * flush () will be cache cleanup!     * Dirty check will be done when the cache is cleaned!     * If the object's properties and previous object properties are inconsistent!     * Then the current object is a dirty object!     * The dirty objects will be synced to the database! * * 03. Free State (off-state) * Once managed by the session!     The difference between the instantaneous state is whether the OID (primary key identifier) exists!  * */@Test public void testSave1 () {//Create an Object Student stu=new Student (100, 50, "old White");   Instantaneous state session.save (STU);          Persistent state stu.setname ("Old Vain");          /** changing the properties of an object this time the Stu is that the dirty object does not need to execute update () commit when it will produce two SQL statements!   01.insert 02.update */@Test public void TestSave02 () {//Create an object StudentStu=new Student (666, 50, "old White");  Instantaneous state stu.setname ("Old Vain");   Instantaneous state session.save (STU);    The persistence state starts here to be managed by the session!  } @Test public void TestSave03 () {//Create an Object Student stu=new Student (555, 50, "old White");  Instantaneous state stu.setname ("Old Vain");   Instantaneous state session.save (STU);        The persistence state starts here to be managed by the session!          Stu.setname ("Old Vain 1");          Stu.setname ("Old Vain 2");          Stu.setname ("Old Vain 3");          /** * or two SQL statements *commit will produce two SQL statements! 01.insert 02.update * * */** * Test method Premise Environment three cases * 01.stu objects do not have corresponding data in the database * 02.     The Stu object has the corresponding data in the database, but we have not modified the property * 03.stu object has corresponding data in the database, we have modified the properties * results are consistent! * Generate Update statements based on ID!     Can only be from the free to lasting!  */@Test public void Testupdate () {//Create an Object Student stu=new Student (1, 50, "old White");     Instantaneous state session.update (STU);   }/** * Prerequisite environment for test method * Stu object does not have corresponding data in the database * Results generated: * 01. Generate Select based on ID  * 02. The discovery database does not have corresponding data to produce insert */@Test public void Testsaveorupdate () {//Create an object Student St  U=new Student (1, 50, "old White");    Instantaneous state session.saveorupdate (STU); }/** * Prerequisite environment for test methods * 01.stu objects have corresponding data in the database * 02. The result of the property value of the Stu object is not changed *: * Generate select language based on ID  Sentence */@Test public void TestSaveOrUpdate2 () {//Create an Object Student stu=new Student (1, 50, "old White");    Instantaneous state session.saveorupdate (STU); }/** * Prerequisite environment for test methods * 01.stu objects have corresponding data in the database * 02. Changed the property value of the Stu Object * Results generated: * 01. Generate SELEC based on ID  T * 02. Perform UPDATE */@Test public void TestSaveOrUpdate3 () {//Create an object because the object's properties have been modified Student  Stu=new Student (1, 50, "old White");        Instantaneous state stu.setname ("Old Vain");    Session.saveorupdate (Stu); }/** * Test method Premise Environment * Stu object does not have corresponding data in database * results: * Two SQL * 01.select first go to the database query Data with ID * 02. Execute Insert */@Test PUBlic void TestMerge01 () {Student stu=new Student (1, 50, "old White");    Instantaneous state session.merge (STU); }/** * Prerequisite environment for test methods * Stu objects have corresponding data in the database, we do not modify the object's properties * Results: * Only SELECT statement */@Test Pub  LIC void TestMerge02 () {Student stu=new Student (1, 50, "old White");    Instantaneous state session.merge (STU);     }/** * Prerequisite environment for test methods * Stu object has corresponding data in the database, we have modified the object's properties * Result: * 01.select * 02.update */  @Test public void TestMerge03 () {Student stu=new Student (1, 50, "old White");        Instantaneous state stu.setname ("Old Vain");    Session.merge (Stu); }/** * Prerequisite environment for test methods * Stu objects have corresponding data in the database, we have modified the object's properties * Results: * ERROR */@Test public V  OID testMerge04 () {Student stu=new Student (1, 50, "old Vain");  Instantaneous state session.merge (STU);  Does not change the state of the object Stu.setname ("Old white 11111");  Instantaneous state session.update (STU); Error}/** * Save (): Converts the transient state to a persistent state * update (): Converts the Free State to a persistentStatus * Saveorupdate (): * Determines whether the save () or update () is executed based on the primary key identifier of the persisted object () * If there is no OID, proving to be instantaneous, execute save ();     * If there is an OID that proves to be in a Free State, execute update ();     * Merge: Although it is consistent with the SQL results generated by saveorupdate ()!     * However: * 01.merge does not change the state of the object!     * 02. When the object is in the instantaneous state, the object is assigned a copy to the session cache, execute save (), produce INSERT statement! * We think that with the INSERT statement, Stu becomes a persistent object!     Not really!     * It's just that the object in the session cache has changed! */            }

/** * First step: *01. Read the configuration file  hibernate.cfg.xml *02. To create a session factory---ensure that the factory is a singleton mode *03. Interface to provide external access * Second Step: *  in the core configuration file Manage our currentsession */public class Hibernatesessionutil {     private  static  configuration configuration;     private static  sessionfactory sessionfactory;          Private  Hibernatesessionutil () {}//privatization construct          //   Execute static code block static{when class is loaded         configuration=new Configuration (). Configure ();         Sessionfactory=configuration.buildsessionfactory ();//Get Session Factory     }      //method of getting sessions public  static Session  getcurrentsession () {         return   sessionfactory.getcurrentsession ();     }               }

New in Hibernate.cfg.xml file

    <!--Configure our Currentsession---    <property name= "Current_session_context_class" >thread</property >

Test code

public class Sessiontest {public    static void Main (string[] args) {        /**configuration configuration=new Configuration (). Configure ();        Sessionfactory sessionfactory = Configuration.buildsessionfactory ();         Session session = Sessionfactory.opensession (); First time         System.out.println (Session.hashcode ());         Session = Sessionfactory.opensession (); Second time         System.out.println (Session.hashcode ());  Hashcode inconsistent                /////////Create currentsession session session with our own created reply factory         = Hibernatesessionutil.getcurrentsession (); First time         System.out.println (Session.hashcode ());         Session =  hibernatesessionutil.getcurrentsession ();//second         System.out.println (Session.hashcode ());// Hashcode the same    }}

/** * The difference between flush and commit!     * * Same point: * Both will sync to the database!  * * different points: * Commit: Save forever!          Commit--->flush ()--Cache cleanup---> Dirty check * flush: not permanently saved!     * 01. Is to perform cache cleanup work! * 02. The objects in the cache will be synced to the database!     But not saved!     * 03. Make sure the data in the cache is consistent with the data in the database!     * * Cache cleanup Mechanism: * When we execute flush (), we will clean up the data in the session!     * Dirty checks are performed when the cache is cleaned!     * Dirty Check: * When the object is managed by the session! * 01.session creates a snapshot of the object in the cache save a State and properties of the object now!     (A object) * 02. When the cache is cleaned, it will compare the properties of the current object with the (a object)! * 03. Find objects now and (a object is inconsistent!)     So now the object is called Dirty Object! * 04.flush () will synchronize this dirty object to the database! But not saved!     It's only temporary!     * 05. You can save the data permanently after the commit! * */@Test public void test01 () {//Get session session by tool class session = Hibernatesessionutil.getcurrent        Session ();        Get transaction Transaction Transaction = Session.begintransaction (); Student stu= (Student) Session.get (Student.class, 1);//Persistent Object Stu.setname ("Can change?        "); /** * Clean Cache * As we understand, no commIt is impossible to commit a transaction! Implication!         The data in the database does not change!        */System.out.println ("*****************");        Session.flush (); Stu.setname ("Can you change the 2?"        ");        System.out.println ("*****************");        Student stu2= (Student) Session.get (Student.class, 1);  System.out.println (Stu2.getname ());    It's changed! } @Test public void test02 () {//Get session session by tool class session = Hibernatesessionutil.getcurr        Entsession ();        Get transaction Transaction Transaction = Session.begintransaction (); Student stu= (Student) Session.get (Student.class, 1);//Persistent Object Stu.setname ("Can change?        ");        System.out.println ("*****************");  Session.flush (); Execute SQL Stu.setname ("Can change 2?")  ");         Then changed the value System.out.println ("*****************");          /** * The OID in the cache is consistent! * GET () * 01. Query Session Cache * 02. Find data in the cache directly using * 03. So the name of STU2 must be "can change 2?" "*/Student stu2= (Student) session.get (Student. class, 1);  System.out.println (Stu2.getname ());    Changed the 2nd time!! }

hibernate04--transitions between three states

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.