Use and Comparison of Methods for operating databases provided by Hibernate

Source: Internet
Author: User

Hibernate provides many methods for object operations. This article briefly introduces the use and comparison of these methods.

Before describing the methods, describe the three states of objects in hibernate: transient, persistent, detached.
Transient: transient or free state.
Persistent: persistence status.
Detached: Out-of-tube or free.

Status judgment:

In general, the object in the session is persistent, clear from the session, and the evict object (including the commit object being removed) is detached. the newly created object and the delete object are in the transient state. however, if a new object has a version field and the version field unsaved-value is different, or the id has a value when assigned by the Code, it is considered as the detached state.

1. persist and save methods:

According to spec, persist does not guarantee immediate execution of the SQL insert statement. save will immediately execute the insert statement.

During use, if the record idIt is not configured as a value for the Code. If it is not<Generator class = "assigned"/> If you assign a value to the oid of the transient or detached object, an exception occurs when you call the persist method:

Org. hibernate. PersistentObjectException: detached entity passed to persist:

If the save method is used, it can be saved successfully, and the assigned oid value does not work.

If the value to be assigned takes effect, use the save (Object, ID) method. You can use the replicate method to perform similar operations.

 

2. saveOrupdate does not save or update the database based on the record or not, but on the object state. If it is a transient object, it is saved. If it is in the detached state, it is updated. it will always trigger the save or update of the hibernate session. for example, if the recorded oidIt is not configured as a value for the Code. If it is not<Generator class = "assigned"/> If a value is assigned to the oid of this object, Hibernate always issues an SQL Update statement. If the database does not have a record corresponding to this oid, no record will be updated, if the oid ValueNullSave.

If the recorded oidConfiguration assigned by code,Is<Generator class = "assigned"/>, ifThe record for the oid does not exist., Save, update if it exists. the oid value must be assigned in the Code; otherwise, an exception occurs: org. hibernate. id. identifierGenerationException: ids for this class must be manually assigned before calling save ():

 

In the same session, saveOrupdate is performed on a transient object. If the oid of this object is exactly the same as the existing object oid in the session, no matterThe mechanism for assigning values to IDS is as follows:

Org. hibernate. NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

(The above rule also applies to the update method)

 

The difference between update and update is that update is always performed based on the oid of the object. For the update method, if no oid is set, an exception occurs:

Org. hibernate. TransientObjectException: The given object has a null identifier:

In a session, an exception occurs when updating the delete obj, for example:

Session. delete (obj );

....

Session. update (obj );

However, objects deleted in another session (or other programs) can be updated, but the database is not changed.

 

 

3. Differences between merge and update and saveorupdate: from the running perspective, the most obvious difference is that if the oid of the update or saveOrupdae object is the same as an object in the session, an exception is thrown, but merge won't.

If the merge object does not exist in the database, a record is saved (similar to saveOrupdate ).

If the session contains instances with the same oid, the state of the merge object will overwrite the old persistent instance.

Hbtest tbo = new Hbtest ();
Tbo. setId (new Integer (100 ));
Tbo. setVal ("val3 ");
SessionFactory. getCurrentSession (). save (tbo );

Hbtest tbo1 = new Hbtest ();
Tbo1.setId (new Integer (100 ));
Tbo1.setVal ("val5 ");
SessionFactory. getCurrentSession (). merge (tbo1); // update database

System. out. println ("******** merge *******" + tbo. getVal (); // The value of tbo is val5.

 

If the session does not have a persistent instance, try to load or create a new persistent instance from the database. The merge method returns the persistent instance.
This object of merge is not associated with the session. It is still free. If it is changed after merge, the value will not be reflected in the database.

 

Hbtest tbo1 = new Hbtest ();

SessionFactory. getCurrentSession (). merge (tbo1 );

...

Tbo1.setVal ("new val"); // it will not be updated to the database.

Changes to the returned object will update the database accordingly.

Hbtest tbo2 = (Hbtest) sessionFactory. getCurrentSession (). merge (tbo1 );

Tbo2.setVal ("new val ");

The role of merge is similar to that of merge provided by the database, such as the merge into Statement of Oracle.

 

It can be seen that merge should be used only when a persistent object with the same identifier already exists in the session, and an error will be reported when saveOrUpdate or update is used. if you are not sure whether the current session has a persistent object with the same identifier and want to update the current object to the (save or update) database, you can use merge.

 

4. The replicate () method uses the values (including oid) of each attribute of the given object to persist the given entity in the Free State. The storage mode must also be specified. replicate checks whether the data already exists in the database with select. If yes, update the data; otherwise, save (when the storage mode is LATEST_VERSION or OVERWRITE ).

Difference from save: If the id already exists, save will have an exception (primary key conflict, org. hibernate. exception. constraintViolationException), when the primary key is not specified by the code, the oid assigned to the save object does not work, but is the responsibility of the hibernate configuration mechanism. replicate performs database operations with the assigned oid.

Difference from update: execute a select statement more than update.

 

In practice, if you want to copy records from one database to another, you can use the replicate method to control the behavior of data conflicts through ReplicationMode.

 

5. delete and evict

Evict: removes the current instance from the session cache. after execution, the object changes will not be synchronized with the database. when the cascade style is evict, the associated objects are cascade. cache is cleared during batch operations to prevent memory shortage.
Delete will also remove the current instance from the session cache, but flunsh will execute the database delete, and then the object becomes a temporary state.

Objects after the delete operation cannot call the update and merge methods, but the saveOrUpdate methods can be used.
It can be seen that compared with evict, delete will not only be deleted from the session, but also from the database.

 

6. load and get

If no matching record is found, the get () method returns null. load () will report ObjectNotFoundEcception. if you use the load method, hibernate deems that the object corresponding to this id (Database record) exists in the database, so it can be safely used, it can safely use a proxy to delay loading the object. The database is queried only when other attribute data in the object is used. However, if the record does not exist in the database, no exception can be thrown, the load method throwing exception refers to throwing an exception when the data of this object does not exist in the database, rather than when the object is created. Since the session cache is a very cheap resource for hibernate, during load, we will first check the session cache to see if the object corresponding to this id exists. If it does not exist, we will create a proxy, the second-level cache and database are queried only when data is actually used. so if you know that this id must have a corresponding record in the database, you can use the load method to implement delayed loading.

The load () method can return the proxy class instance of the object, while get may return the entity class or the proxy class. if the get method finds the object corresponding to this id in the session cache, if the object is replaced by a proxy, for example, it is used by the load method, or delayed loading by other associated objects, the returned result is the original proxy object instead of the Object Class Object, if the proxy object has not loaded Entity Data (that is, attribute data other than id), it will query the second-level cache or database to load data, but the returned result is still a proxy object, however, Entity Data has been loaded.

 

7. query list and iterate methods: the list method retrieves data at a time. The iterate method first obtains the id and then obtains data multiple times based on the id. refer

 

8. clear, evict, and flush methods of the Session
The clear () method clears all objects (including various States) in the Session-level cache to release the memory.
The evict () method clears the specified object (including various States) in the Session-level cache.
Flush () forces persistence of the object in the Session cache and does not clear the object from the cache.

 

SessionFactory. getCurrentSession (). save (tbo1 );

SessionFactory. getCurrentSession (). flush (); // Execute SQL. If flush is not executed before clear, tbo1 will not be saved to the database.

SessionFactory. getCurrentSession (). clear ();

 

SessionFactory. getCurrentSession (). save (tbo1 );
SessionFactory. getCurrentSession (). flush ();
SessionFactory. getCurrentSession (). evict (tbo1); // If flush is not executed before evict, an exception occurs.

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