Java framework --- session Status of hibernate, hibernatesession

Source: Internet
Author: User

Java framework --- session Status of hibernate, hibernatesession

Session interface is the most important interface that Hibernate provides to the program to manipulate the database,Is a single-threaded objectIt provides basic methods for saving, updating, deleting, and querying. It has a cache that stores persistent objects. When the cache is cleared, the database is synchronously updated based on these persistent objects.

Note: Some session methods (persist, load) do not immediately write changes to the database, but cache the changes to the session level-1 cache, unless flush is called, or the session will be updated to the database only when the session is closed.

Session Methods

1. Save

Save: insert the database immediately and return the primary key.

Persist: no immediate (delayed) database insertion, no return value

2. Get

Load: After an object is loaded, changes to the object are not immediately refreshed to the db, and must be flushed to the db.

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

User. setName ('gt ');

User. flush (); (delayed loading)

Get: After the object is loaded, changes to the object are immediately refreshed to the db

3. Update

Update: persistence object, update

SaveOrUpdate: includes the save () and update () functions. If the input parameter is a temporary object (not saved), the save () method is called. If the input parameter is a free object, call the update () method.

Merge: Does not persist objects, but updates modifications to managed objects to db.

4. Delete

Delete: delete the records corresponding to the JAVA object from the database.

 

5. Clean up

Flush: Synchronize cache to db

Clear: clears the cache size of the session (this should be considered during batch update)

 

Transition Relationship between three States

The following is an example:

Entity:

package cn.itcast.h_session_method;public class User {    private Integer id;    private String name;    private byte[] data = new byte[1024 * 1024 * 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;    }}

Ing file:

<? Xml version = "1.0"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing 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.hibernate.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 the persistent state (handed over to Sessioin Management) // insert... @ Test public void te StSave () throws Exception {Session session = sessionFactory. openSession (); session. beginTransaction (); // ---------------------------------------------- User user = new User (); // temporary state user. setName ("test"); session. save (user); // change to the persistent State // ------------------------------------------------ session. getTransaction (). commit (); session. close (); user. setName ("Li Si"); // The System is in the Free State. out. println (user. getName ()); // Free state} // update (): changes the free state to a persistent state. // update is generated... // when the object does not exist, the error @ Test public void testUpdate () throws Exception {Session session = sessionFactory is returned. openSession (); session. beginTransaction (); // ------------------------------------------------ User user = (User) session. get (User. class, 1); System. out. println (user. getName (); // persistence status // session. clear (); // clear all objects in the Session. evict (user );// Clears a specified object user in the Session. setName ("newname3"); session. update (user); System. out. println ("----"); // session. flush (); // fl to the database // ------------------------------------------------ session. getTransaction (). commit (); // session. close ();} // saveOrUpdate (): Convert the temporary or free state to the persistent state. // insert into or update will be generated... // when the object does not exist, an error is reported. // This method determines the status of the object based on the id. If the id is the original value (the object is null, the value of the original type is 0), which is a temporary state. If it is not the original value, it is a free state. @ Test public void testSaveOrUpdate () throws Exception {Session session = sessionFactory. openSession (); session. beginTransaction (); // ------------------------------------------------ User user = new User (); user. setId (3); // generate a user in the Free State object. setName ("newName"); session. saveOrUpdate (user); // ------------------------------------------------ session. getTransaction (). commit (); session. close ();} // delete (): Convert persistence or freeze to the deletion status. // A: delete will be generated... // If the deleted object does not exist, an Exception @ Test public void testDelete () throws Exception {Session session = sessionFactory will be thrown. openSession (); session. beginTransaction (); // ---------------------------------------------- // User user = (User) session. get (User. class, 2); // persistent User user User = new user (); User. setId (300); session. delete (user); session. flush (); System. out. println ("---");//----- --------------------------------------- Session. getTransaction (). commit (); session. close ();} // get (): get data, which is a persistent State // will generate: select... where id =? // The SQL statement will be executed immediately // if the data does not exist, null @ Test public void testGet () throws Exception {Session session = sessionFactory will be returned. openSession (); session. beginTransaction (); // ------------------------------------------------ User user = (User) session. get (User. class, 5); // persistence System. out. println (user. getClass (); // System. out. println ("---"); // System. out. println (user. getName ());//--------------------------------- ----------- Session. getTransaction (). commit (); session. close ();} // load (): obtains the data in the persistent state. // select is generated... where id =? // After load (), a proxy object is returned, which requires that the class cannot be final. Otherwise, the subclass proxy cannot be generated and the lazy loading function cannot be used. // Lazy loading failure method: 1. Write the entity as final; 2. In hbm. write <class... lazy = "false"> // The SQL statement will not be executed immediately. Instead, the SQL statement is executed 1st times when the non-id or class attribute is used. // If the data does not exist, an Exception is thrown: ObjectNotFoundException @ Test public void testLoad () throws Exception {Session session = sessionFactory. 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 ();} // operate on a large amount of data. To prevent too many objects in the Session from causing memory overflow @ Test public void testBatchSave () throws Exception {Session session = sessionFactory. openSession (); session. beginTransaction (); // -------------------------------------------- for (int I = 0; I <30; I ++) {User user = new User (); user. setName ("test"); session. save (user); if (I % 10 = 0) {session. flush (); // first fl the session. clear (); // clear again} // -------------------------------------------------- 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); // persistence System. out. println (user. getName (); // session. clear (); // user = (User) session. get (User. class, 5); // persistent session. refresh (user); // refresh the state of the object in the Session cache, that is, re-select the System. out. println (user. getName (); // ------------------------------------------------ session. getTransaction (). commit (); session. close ();}}

For a newly created object, if the object does not exist in the session and database, the object is a temporary object (Transient)

When a temporary object calls the save method or a free object calls the update method, the object becomes a persistent object. If the object is a persistent object, any modifications to the object are made, will be compared with when the transaction is committed. If it is different, an update statement will be sent; otherwise, the statement will not be sent.

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

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.