[SSH] -- Conversion between three statuses of Hibernate
Hibernate has three statuses: transient, persistent, and detached. The understanding of these three states can be combined with the Session cache. The state in the Session cache is persistent, and the other two are not in the Session.
Another way is to add a removed state to Hibernate in four states. When a session instance is deleted in the cache, it is converted to this status.
Transient
Created through new (), which is not in the cache of the session and is not related to the database. Objects in this state are called temporary objects.
Persistent
The object is in the session cache, and data in the database corresponds to it.
Detached
This object exists in the database, but does not exist in the session.
Is the conversion between the three States. Let's take a look at it through the instance. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KCjxibG9ja3F1b3RlPgogIDxwPjGhor + placement = "brush: java;"> Private static SessionFactory factory;/*** initialize sessionFactory */static {try {// read hibernate. cfg. xml Configuration file Configuration cfg = new Configuration (). configure (); // create sessionFactory to access mysql factory = cfg. buildSessionFactory ();} catch (Exception e) {e. printStackTrace ();} finally {}} // obtain the session public static Session getSession () {return factory. openSession ();}
Get session Object
// Obtain the session object session = HibernateUtil. getSession (); // enables ts = session. beginTransaction (); // Transient state user = new User (); user. setName ("Zhang San"); user. setPassword ("1233"); user. setCreateTime (new Date (); user. setExpireTime (new Date ());
After the new () method is executed, the object enters the transient state. We can also see that if you do not operate on the object next, the object will be eventually reclaimed, and it is no longer in the transient state.
Next, we will perform a simple save () operation on it.
2. transient --> persistent
// After execution, the Persistent session is managed by the session. save (user); // modify the user name user. setName ("Zhang Si"); // commit synchronizes data with the database. Ts. commit ();
3. persistent --> detached
Close the session and change the object state from persistent to free.
if(session!=null){ if(session.isOpen()){ session.close(); } }
4. detached --> persistent
Here, we use the update () method.
// Modify the user name again. setName ("Zhang Wu"); // obtain the session object, which is similar to session = HibernateUtil. getSession (); // enables ts = session. beginTransaction (); // change session management // to persistent state, and synchronize the database when cache is cleared. Session. update (user); session. getTransaction (). commit ();
Understanding the three states of objects in Hibernate can help us perform flexible operations on them. It can also help us understand the association between session cache and database.