How jsp hibernate saves data

Source: Internet
Author: User

Save, update, and delete data:
1. Session. save () method:
The Session. save () method is used to persistently store object objects. That is to say, when session. save () is executed, an insert SQL statement is generated to save data. The following code:
User user = new User ();
User. setName ("zx ");
Transaction tx = session. beginTransaction ();
Session. save (user );
Tx. commit ();
When the session is executed. in the save () method, Hibernate does not immediately generate an insert SQL statement for data storage. Instead, it is possible to execute the insert SQL statement when the session cache is cleared later. what steps will the save () method perform? The following is a summary:
1. Search for the saved object in the internal cache of the session. If the object is found, it is deemed that the data has been saved (the insert operation has been executed). The object is already in the persistent State and is directly returned. At this time, even if the data status changes compared to the previous one, the dirty data check will be performed during the transaction commit to determine whether the update operation is required.
2. If the object implements the lifecycle interface, the onSave () method of the object to be saved is executed.
3. If the object implements the Validatable interface, the corresponding validate () method will be executed.
4. If an Interceptor object exists, the Interceptor. onSave () method is executed.
5. Construct an insert SQL statement to save the data.
6. After the data is successfully saved, set the Object id to the id of the inserted record.
7. Add the saved object to the internal cache of Hibernate (level-1 cache ). Note that Hibernate does not include the saved object in the second-level cache, because the saved object is likely to be modified later, the cache is frequently updated, and the synchronization cost is caused, beyond the benefits of caching this object.
8. If the object has an associated object, it will recursively process the cascading object.

1. Session. update () method:
As I have mentioned earlier in the object state transition section, the session. update () method can re-incorporate an object in the Free State into the internal cache of Hibernate and turn it into a persistent object. The following code:
Configuration cfg = new Configuration ();
SessionFactory sf = cfg. configure (). buildSessionFactory ();
Customer customer = new Customer ("zx", 27, images); // The customer object is in the Free State.
Session session = sf. openSession ();

Transaction tx = session. beginTransaction ();
Session. save (customer); // after saving, the customer object is in the persistent state.
Session. flush (); // After clearing the cache, the customer object is in the Free State.
Tx. commit ();
Session. close ();

Session session2 = sf. openSession ();
Transaction tx2 = session2.beginTransaction ();
Session2.update (customer); // call the update () method to convert the customer object in the Free State to the persistent state again.
Session2.delete (customer); // After the delete () method is called, when the cache is cleared, the customer object is removed from the cache and a delete transaction is generated in the database, to delete the data records corresponding to the customer object.
Tx. commit ();
Session. close ();
So what steps have this method taken? It performs the following operations:
1. First, we will find the object to be updated in the cache. If we find it, we will return immediately. From here we can see that if we execute the update () method on an object already in the persistent, will not have any effect.
2. When the committed transaction is cleaned up by cache, the changed attributes are checked through dirty data, and the update SQL statement is generated to update the data.
There is a problem here that we should emphasize that as long as a free object is associated with the session through the update () method, no matter whether the attribute of the Free object is changed, the update SQL statement is executed. The following code:

Transaction tx = session. beginTransaction ();
Session. update (customer );
Tx. commit ();
Session. close ();
In this Code, no attribute values of the customer object are modified, but an update SQL statement is also executed. If you do not want to execute the update SQL statement without changing the attribute values of the object, you must enable the select-before-update attribute of the <class> element of the object and set it to "true". The default attribute is "false ". Configure as follows:
<Class name = "com. neusoft. entity. Customer" table = "customer" select-before-update = "true">
If this attribute configuration is enabled, the following SQL statement is executed before session cache is cleared:
Select * from customer where id = '1 ';
Query the attribute values of the customer entity in the database, and compare them with the cached attribute values one by one. If the value changes, an update operation is generated to update the data, if there is no change, the update operation will not be performed. You need to determine whether to enable this option based on actual requirements. If the attributes of an object do not change frequently, you should enable this option to avoid unnecessary update operations. If the attributes of an object change frequently, you do not need to enable this option to execute unnecessary select statements before executing the update operation.

Note: (1) When session. update () is performed on a free object, if the record corresponding to this object does not exist in the database, this operation will throw an exception.
(2) When the session is executed. when the update () method associates a free object with the session, if a persistence object with the same OID as the object already exists in the cache, this method throws an exception. The following code is used:
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 we associate the free object customer1 with session2 again, an othercustomer object with the same OID as customer1 has been loaded in the cache due to the load () operation, in this case, an exception is thrown because the object cache mechanism cached by Hibernate does not allow caching objects with the same OID.
2. Session. saveOrUpdate ():
This method includes the features of the save () method and the update () method. If the method is passed in as a free object, this method will perform the update operation, if the method is a temporary object, this method will execute the insert operation. The working principle behind this method is as follows:
A) First, search for the cache. If the operation to be saved is found, the system returns the result directly.
B) if the entity implements the interception method, the isUnsaved () method is executed to determine the object state.
C) if the object is in the temporary state, save () is executed. if the object is in the Free State, update () is executed ().
There is a problem here, that is, how does Hibernate determine whether an object is in the free or temporary state? If an object meets the following conditions, it is considered to be in a temporary state.
The oid value of the. Java object is null.
. If the Java object has the version attribute (which will be explained in the concurrent locking Section) and is null.
. If the <id> attribute unsaved-value of the object is set, and the OID value is equal to the unsaved-value.
. If unsaved-value is set for the version attribute of an object, and the value of the version attribute is equal to that of the unsaved-value.
. If the entity implements Interceptor and the Interceptor. isUnsaved () method returns true.
If one of these conditions is met, this entity is considered a temporary object.
3. Session. delete ():
The delete () method is used to delete data corresponding to one or more objects from the database. If the input object is a persistent object, the delete operation is executed when the cache is cleared. If the input is a free object, it will first associate the object with the session, and then execute the delete operation when the cache is cleared. See the following code:
Session session = sessionFactory (). openSession ();
Transaction tx = session. beginTransaction ();
Customer customer = (Customer) session. load (Customer. class, "1 ");
Session. delete (customer); // execute a delete statement.
Tx. commit (); // clear the cache and execute a delete statement.
Session. close (); // close the session. The customer object will be deleted from the cache.
If the customer object in the above Code is a free object, the session is executed. the delete () method first associates the free customer object with the session, and then clears the cache before executing the delete operation. If you want to delete multiple data records 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 conditions.

Related Article

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: 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.