Save, update, and delete Hibernate data

Source: Internet
Author: User
Tags flush

data Save, update, and delete:    1 , Session.save () Method: Session.save () method is used for persistent preservation of entity objects, that is, when executing Session.save () method is generated when the corresponding Insert SQL statement to complete the preservation of the data. As in the following code: User User=new User (); User.setname ("ZX"); Transaction tx=session.begintransaction (); session.save (user); tx.commit (); when executing to Session.save () method, Hibernate will not be generated immediately Insert SQL statement to save the data, but when you later clean the Session can be executed when the cache is Insert SQL statement, then Session.save () What steps will the method perform? Take a look at the following summary: One, in the Session 's internal cache to find the saved object and, if found, the data is considered saved (once executed Insert action), the entity object is already in the Persistent state, return directly. At this point, even if the data has changed before, the dirty data will be checked at the time of the transaction to determine whether to perform Update operation. Second, if the entity object implements the Lifecycle interface, the object to be saved is executed OnSave () method. Third, if the entity object implements the validatable interface, you will perform the corresponding Validate () method. Four, If an Interceptor object exists, the Interceptor.onsave () method. Five, Construction Insert SQL statement to complete the data save. Six, after the data has been saved successfully, set the entity object's ID for inserting records. ID . Seven, to incorporate the saved entity objects into the Hibernate Internal cache (first-level caching). Attention Hibernate The saved entity objects are not included in the level two cache, because the entity objects that have just been saved are likely to be modified later, the cache is frequently updated and the resulting synchronization problem costs more than the benefits of caching the object. Eight, Finally, if the object is associated with the object, the cascading object is recursively processed.   1, session.update () Method:    I have said before in the Entity Object State Transformation section, session.update () method is able to integrate an object that is in a free State into Hibernate internal cache and becomes a persisted object. As in the following code: Configuration cfg = new Configuration (); sessionfactory sf=cfg. Configure (). Buildsessionfactory (); Customer Customer=new Customer ("ZX", 27,images); Customer object is in a Free State Session Session=sf.opensession ();   Transaction tx=session.begintransaction (); Session.save (customer);/ after saving Customer object in persistent state Session.flush ()// after emptying the cache Customer object is in a Free State tx.commit (); session.close ();   Session Session2=sf.opensession (); Transaction tx2=session2.begintransaction (); session2.update (customer);/ by calling Update () method will free the state of the Customer object, converted again to a persisted state Session2.delete (customer);/ Call Delete () method, when the cache is emptied, the Customer object is moved out of the cache and generated in the database Delete transactions, to remove Customer object corresponding to the data record tx.commit (); session.close (); So what steps does this approach perform? It will follow the steps below: One, First we look in the cache for the entity object that needs to be updated, and if we find it, we return it immediately, from where we can see if the Persistent the Entity object Execution Update () method, will not have any effect. Second, then, when the transaction is committed for cache cleanup, the changed properties are determined by the dirty data check, and then generated Update SQL statement to complete the update of the data. Here's a question we'd like to emphasize is that just through Update () method to associate a free object with the Session associated, then regardless of whether or not the properties of this free entity object are changed, they are executed Update SQL statement. As in the following code:   Transaction tx=session.begintransaction (); session.update (customer); tx.commit (); session.close (); There is no modification in this code. Customer object, but it also executes a property value of the Update SQL statement, if you want to not do so without changing the value of the entity object attribute Update SQL statement, then you have to open the entity object <class> Elements of "Select-before-update" property to set it to "true", This property defaults to "false" . Configure as follows: <class name= "Com.neusoft.entity.Customer" table= "Customer" select-before-update= "true" > If this property configuration is enabled, then the cleanup Session before caching, you will first execute a line similar to the following SQL statement: Select * from customer where id= ' 1 '; all of the query Office Customer The entity's corresponding property value in the database, and then each is compared to the value of the property in the cache, and if a change occurs, it will generate Update operation to update the data, if not changed then will not be done Update operation. To determine whether or not to turn this option on according to the actual requirements, if the entity object's properties do not change frequently, then this option should be turned on to avoid the execution of redundant Update operation. If the properties of the entity object change frequently, then there is no need to turn on this option to avoid executing Update before you perform an extra Select statement.   Note: ( 1 when executing on a free entity object session.update () operation, if there is no record of this entity in the database, the operation throws an exception.    ( 2 ), when executing session.update () method to associate a free object with the Session Association, if it already exists in the cache at this time, the entity object has the same OID is persisted, this method throws an exception. Like the following code: Customer Customer1=new Customer ("1", "ZX", 27,images); Session Session1=sf.opensession (); Transaction tx=session1.begintransaction (); Session.save (customer1); Session.flush (); tx.commit (); session1.close ();   Session Session2=sf.opensession (); Transaction tx2=session2.begintransaction (); Customer othercustomer= (customer) Session2.load (Customer.class, "1"); session2.update (customer1) tx2.commit (); session2.close (); when again the free object Customer1 with Session2 Association, this is because load () operation, in which the cache has already loaded A and Customer1 have the same OID of the Othercustomer object, at this time because Hibernate the cached object caching mechanism does not allow the OID the same object cache, so an exception is thrown. 2, session.saveorupdate (): This method contains the Save () Methods and Update () method, if the method is passed in a free object, then this method executes the Update action, if the method is passed in as a temporary object, then the method executes the Insert operation. The method behind the scenes works as follows: a) first look in the cache and return directly if you find the operation you want to save. b) if the entity implements the interception method, it executes the isunsaved () method to determine the state of the entity object. c) executes if the entity is in a temporary state Save (), if the entity is in a free state then it executes Update () . There is a problem here, that is Hibernate is how to determine whether an entity is in a free State or a temporary condition. If the entity satisfies one of the following conditions, the entity is considered to be in a temporary state. . Java object's OID value is NULL . . if Java object has version property (which will be explained in the Concurrent lock section) and is NULL . . if the entity's <id> Set the Properties Unsaved-value , but OID Values and Unsaved-value values are equal. . if the entity's version property to set the Unsaved-value , and version property is the value of the Unsaved-value values are equal. . if the entity implements the Interceptor, and interceptor.isunsaved () method returns true . to satisfy one of these conditions, this entity is considered a temporary object. 3, session.delete (): Delete () method is used to delete data for one or a group of entities from the database, and if the incoming object is a persisted object, when the cache is cleaned, it executes the Delete operation. If a free object is passed in, the object is first made with the Session associated, and then when the cache is cleaned up, execute the Delete operation. Look at the following code: Session Session=sessionfactory (). Opensession (); Transaction tx=session.begintransaction (); Customer customer= (customer) Session.load (Customer.class, "1"); Session.delete (customer);/ plan to execute a Delete Statement tx.commit ()// cleans up the cache and executes a Delete Statement session.close ()// off Session , At this time will be put Customer object is removed from the cache. if the code in the above Customer object is a free object, then when executing Session.delete () method, the first will be the free Customer Objects and Session associated, and then clean the cache, then execute the Delete operation. If you want to delete more than one piece of data at a time, you can use an overloaded Delete () Method: Delete ("from Customer C where c.id> ' 8 '"); This method can delete all data that meets the criteria.

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.