"Hibernate Step by Step"--core object + Persistent object Total analysis (II.)

Source: Internet
Author: User

In the previous article, we discussed the core objects of hibernate, which are used frequently in the development process, such as JTA, Sessionfactory, Session, and JDBC, in which sessionfactory can be regarded as the image of the database. Use it to create a session object. JTA is used to manage transactions that are synchronized to the database after the object model changes. There is also hibernate as the persistence layer which encapsulates the transformation process of the persistence layer. The following focuses on the conversion process for persistent objects.


first, State analysis
 Hibernate's persistent objects are mainly divided into three states, Transient, persistent, Detached. In which transient is called transient and is not managed by the database, Hibernate does not assign an ID to the object, does not have a corresponding row in the database, and is generally converted to transient after the new object is created; persistent is called persistence. This is now managed by the session. Hibernate assigns an ID to the object (which can be manually or voluntarily assigned using other methods, the type of the ID can be configured in User.hbm.xml), and a row is already in the database, which is committed to the database after the session's Save method is invoked. Detached is called a de-tube object. At this point, the changes have been synchronized to the database, it has hibernate assigned ID, but at this time the ID is in the persistence State allocation, in the programming of this state object is often not subject to the session management. Suppose you want to change again to create a session again and then manage the object. Transient, detached objects are assumed to be unused for a long time. will be recycled by Java's garbage collector at some time.
1, Transient: Not in the database, not by the session management
It is not difficult to see from Hibernate's architecture diagram. The transient of an object is completed in the application, and when the object is created, it transitions to transient, and there is no persistence process. This means that there is no persistence indicator (ID number. Hibernate assigns an ID to the object when it creates the persisted object. Guaranteed uniqueness).

The transient object assumes no matter what the operation is. Will die at some point and be recycled by the Java garbage collector.



Example: Add a method named TestSave1 to the Sessiontest code, such as the following:

public void TestSave1 () {Session session=null; Transaction tx = Null;try{session=hibernateutils.getsession ();//Open Transaction tx= session.begintransaction ();// Transient state user user=new User (); User.setname ("Zhangsi"); User.setpassword ("123"); User.setcreatetime (new Date ()); User.setexpiretime (New Date ());} catch (Exception e) {e.printstacktrace (); if (tx! = null) {Tx.rollback ();}} Finally{hibernateutils.closesession (session);} Detached status}

Set a breakpoint at the Save method to perform debugging. The output results are for example:

2, persistent: The database has, was managed by the session
A transient object needs to be saved after operation, when the call to save or other Save method is converted to a persistent object, hibernate to the object to create a persistent flag, and may have a corresponding row in the database, And the indicator is equivalent to the Java label, which indicates where the object is in memory.

Another object that is not created has the same ability to use other methods to directly convert to that state, such as get, load, and so on.

If the object of the persistent state is changed. The changes are synchronized to the database when the memory is cleaned or when the dirty data is checked. Then two statements are generated, insert and update, respectively.

Add the SaveTest2 method to the Sessiontest. Test persistent State

public void TestSave2 () {Session session=null; Transaction tx = Null;try{session=hibernateutils.getsession ();//Open Transaction tx= session.begintransaction ();// Transient state user user=new User (); User.setname ("Zhangsi"); User.setpassword ("123"); User.setcreatetime (new Date ()); User.setexpiretime (New Date ())),//persistent state//persistent state object, when the object's properties are changed//hibernate when the cache is cleaned (dirty data check), is synchronized with the database Session.save (user), User.setname ("Lisi"), or the Udpdate method that is capable of displaying the call, because it is a persistent state at this time. Calling udpate does not make sense session.update (user); Tx.commit ();} catch (Exception e) {e.printstacktrace (); if (tx! = null) {Tx.rollback ();}} Finally{hibernateutils.closesession (session);}
}

The persisted state entered after the Save method is called. In this case, the user object has been added ID identification: The method after the completion of the database will be added to a new message, careful child shoes can see the method called two times SetName method. What is the final result? View the tables in MySQL to see:
The last message added to the database is Lisi, so it finally runs the update operation, where two SQL statements are printed in the console, insert and UPDATE statements, respectively.


Note: Before committing the transaction or closing the session. The Flush method of the session is called to operate on each change.


3, Detached: the database has. Not managed by the session
The objects in the off-tube state are in fact mapped to the database. It's just that it's not recycled at this point in the garbage collection period. The object at this point has a persistent identity. The identity corresponds to a row in the database, but the identity is not guaranteed to correspond to the Java identity.
Add the TestSave3 method to the Sessiontest class. Test the detached state of the object and the database, code such as the following:

public void TestSave3 () {Session session=null; Transaction tx = NULL; User user=null;try{session=hibernateutils.getsession ();//Open Transaction tx= session.begintransaction ();//transient status user= New User (); User.setname ("Zhangsi"); User.setpassword ("123"); User.setcreatetime (new Date ()); User.setexpiretime (new Date ());//persistent the state//persistent the state of the object. When the object's properties are changed,//hibernate is synchronized with the database Session.save (user) when the cache (dirty data check) is cleaned, user.setname ("Lisi"); Tx.commit ();} catch (Exception e) {e.printstacktrace (); if (tx! = null) {Tx.rollback ();}} Finally{hibernateutils.closesession (session);} Detached status User.setname ("Wangwu"); Try{session=hibernateutils.getsession (); session.begintransaction ();// The object of the detached state is again included in Session Management//object that will become persistent state object//persistent state, when the cache is cleaned and the database is synchronized session.update (user); Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}

When you are finished running, review the information in the database, for example:

Analysis of the results of the operation, it is not difficult to find that it is the last update operation, the difference is that the detached state of the object must again define a new session object, because the session object thread is not secure. Easy error.



Conclusion
This paper mainly discusses the process of the state transformation of Hibernate persistent objects throughout the declaration cycle, which makes the relationship model and the object model closely related, and also uses the configuration file to manage these states, which makes hibernate easy to operate. and powerful. The above is just a preliminary analysis of several states of persistent objects. There is also a conversion method between states that will be discussed in the next article.

"Hibernate Step by Step"--core object + Persistent object Total analysis (II.)

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.