Session State of Java Hibernate

Source: Internet
Author: User

The session interface is the most important interface that hibernate provides to the program to manipulate the database, and is a single-threaded object that provides basic methods for saving, updating, deleting, and querying. It has a cache that holds persisted objects and updates the database as they are synchronized when the cache is cleaned up.

Note: Some methods of the session (Persist,load) do not immediately write changes to the database, but are cached in the session's first-level cache, unless the display calls flush, or when the session is closed, updates to the database

    1. Temporary status (Transient): not associated with session
    2. Persistent State (persistent): associated with session, not close
    3. Free State (Detached): When Session.close
A detailed approach to the session

1. Save

Save: Inserts the database immediately and returns the primary key

Persist: Do not immediately (delay) Insert database, no return value

2. Get

Load: After loading the object, changes to the object are not immediately flushed to the DB and must be flush to db

Ex:user user=session.load (user.class,2);

User.setname (' GT ');

User.flush (); (Lazy Loading)

Get: Changes to the object are immediately flushed to the DB after the object is loaded

3. Update

Update: Persistent object, updating

Saveorupdate: Contains the Save () and update () functions, and calls the Save () method if the passed parameter is a temporary object (not saved), or the update () method if the passed argument is a free object

Merge: Object is not persisted, only changes to the managed object are updated to DB

4. Delete

Delete: delete records from the database that correspond to Java objects

5. Cleaning up

Flush: Synchronizing the cache to DB

Clear: Clear the cache size of session (should be considered when updating batches)

Transition relationships for three states

The following examples illustrate:

Entity:

Package Cn.itcast.h_session_method;public class User {    private Integer ID;    private String name;    Private byte[] data = new byte[1024 * 1024x768 * 5];    Public Integer getId () {        return ID;    }    public void SetId (Integer id) {        this.id = ID;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }}

Map file:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public        "-//hibernate/hibernate mapping DTD 3.0//en"        "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">

Configuration file: Hibernate.cfg.xml

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibern Ate.org/dtd/hibernate-configuration-3.0.dtd ">

Test file

Package Cn.itcast.h_session_method;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Org.junit.test;import Com.java1234.util.hibernatesessionfactory;public    Class App {private static Sessionfactory Sessionfactory = Hibernatesessionfactory.getsessionfactory ();        Save (): Changes the temporary state to a persistent state (to Sessioin Management)/generates: INSERT INTO ... @Test public void Testsave () throws Exception {        Session session = Sessionfactory.opensession ();        Session.begintransaction (); --------------------------------------------User user = new user ();        Temporary state user.setname ("test"); Session.save (user);        becomes persistent state//--------------------------------------------session.gettransaction (). commit ();        Session.close (); User.setname ("John Doe"); Free State System.out.println (User.getname ()); Free State}//Update (): Changes the Free State to a persistent state//generates: Update ...//When the object does not exist when updating, the error @Test public void Testupdate () throws Exception {Session session = Sessionfactory.opensession ();        Session.begintransaction ();        --------------------------------------------User user = (user) Session.get (user.class, 1); System.out.println (User.getname ()); Persistent state//session.clear (); Clears all objects in the session session.evict (user);        Clears a specified object in session user.setname ("Newname3");        Session.update (user);        SYSTEM.OUT.PRINTLN ("----"); Session.flush (); Swipe out to Database//--------------------------------------------session.gettransaction (). commit ();    Session.close (); }//Saveorupdate (): Turn temporary or free status to persistent state//generate: INSERT INTO or update ...//when updating, the object does not exist on the error//This method is based on the ID to determine what the object is state: if I    D is the original value (the object is null, the original type number is 0) is the temporary state, if not the original value is the Free State.        @Test public void Testsaveorupdate () throws Exception {Session session = Sessionfactory.opensession ();        Session.begintransaction (); // --------------------------------------------User user = new user (); User.setid (3);        Self-generated a Free state object User.setname ("NewName");        Session.saveorupdate (user);        --------------------------------------------session.gettransaction (). commit ();    Session.close (); }//Delete (): Convert persistent or free to delete state//Generate: Delete ...//If the deleted object does not exist, it will throw an exception @Test public void Testdelete () throws Exc        Eption {Session session = Sessionfactory.opensession ();        Session.begintransaction (); --------------------------------------------//user user = (user) Session.get (user.class, 2);        Persistent user user = new user ();        User.setid (300);        Session.delete (user);        Session.flush ();        SYSTEM.OUT.PRINTLN ("---");        --------------------------------------------session.gettransaction (). commit ();    Session.close ();    }//Get (): Gets data, is persisted state//generates: Select ... where id=? Executes the SQL statement immediately//returns NULL if the data does not exist @Test public VOID Testget () throws Exception {Session session = Sessionfactory.opensession ();        Session.begintransaction (); --------------------------------------------User user = (user) Session.get (user.class, 5);        Persistent System.out.println (User.getclass ());        SYSTEM.OUT.PRINTLN ("---");        System.out.println (User.getname ());        --------------------------------------------session.gettransaction (). commit ();    Session.close ();    }//Load (): Gets data, is persisted state//generates: Select ... where id=?    Load () Returns a proxy object that requires that the class not be final, or the subclass proxy cannot be generated, and lazy loading is not allowed.    Let lazy load failure way: First, the entity written final; second, write <class in Hbm.xml ... lazy= "false" >//does not execute SQL statements immediately, but executes SQL the 1th time when a non-ID or class attribute is used. If the data does not exist, throw an exception: objectnotfoundexception @Test public void TestLoad () throws Exception {Session session = SES        Sionfactory.opensession ();        Session.begintransaction (); --------------------------------------------User user = (user) SessiOn.load (User.class, 5);        System.out.println (User.getclass ());        SYSTEM.OUT.PRINTLN ("---");        System.out.println (User.getid ());        System.out.println (User.getname ());        System.out.println (User.getname ());        --------------------------------------------session.gettransaction (). commit ();    Session.close (); }//Manipulate large amounts of data to prevent excessive objects in the Session and memory overflow @Test public void Testbatchsave () throws Exception {Session session = SE        Ssionfactory.opensession ();        Session.begintransaction (); --------------------------------------------for (int i = 0; i < i++) {User user = new User ()            ;            User.setname ("test");            Session.save (user);        if (i% = = 0) {Session.flush ();///Brush out session.clear ();//Re-empty}}        --------------------------------------------session.gettransaction (). commit ();    Session.close ();  } @Test  public void Test2 () throws Exception {Session session = Sessionfactory.opensession ();        Session.begintransaction (); --------------------------------------------User user = (user) Session.get (user.class, 5);        Persistent System.out.println (User.getname ());        Session.clear (); user = (user) Session.get (user.class, 5); Persistent Session.refresh (user);        Refreshes the state of the object in the session cache, that is, re-select SYSTEM.OUT.PRINTLN (User.getname ());        --------------------------------------------session.gettransaction (). commit ();    Session.close (); }}

For an object that has just been created, if the object does not exist in the session and in the database, then the object is a temporary object (Transient)

The temporary object calls the Save method, or the free object calls the Update method to make the object a persisted object, and if the object is persisted, any modifications to that object will be compared to it when the transaction is committed and, if different, an UPDATE statement is sent. Otherwise, the statement will not be sent

The free object is that the database exists, but the object is not hosted by the session

Session State of Java Hibernate

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.