CRUD operations on Hibernate objects

Source: Internet
Author: User

CRUD operations on Hibernate objects
1. CRUD operation of the Hibernate object 1.1. Three states of the object

Transient-objects created by the new operator and not associated with HibernateSession are considered as Transient. The instantaneous object is not persisted to the database, nor is it assigned a persistent identifier (identifier ). If the instantaneous object is not referenced in the program, it will be destroyed by the garbage collector. You can use Hibernate Session to change it to a Persistent state. (Hibernate will automatically execute necessary SQL statements)

Persistent instances have corresponding records in the database and have a Persistent identifier (identifier ). Persistent instances may be saved or loaded. Either of them exists within the scope of the associated Session by definition. Hibernate detects any changes to objects in the Persistent state, and sets the object data (state) when the current unit of work is completed) synchronize ). Developers do not need to manually execute UPDATE. You do not need to manually execute the DELETE statement to change the object from Persistent to Transient.

Detached-after the Session associated with the Persistent object is closed, the object becomes Detached. The reference to the Detached object is still valid, and the object can be modified. If a Detached object is re-associated to a new Session, it will be converted to a Persistent object (changes during the Detached will be persisted to the database ). This feature makes it possible to develop a programming model that allows users to think about the unit of work (unit of work) that runs for a long time (user think-time. We call it an application transaction, which is a unit of work from the user's point of view ).

// Read the Configuration file to obtain the Configuration object

Configuration config =NewConfiguration (). configure ();

// Obtain the session Factory

SessionFactory sf = config.BuildSessionFactory();

Session session = sf. openSession ();

Sf. getCurrentSession ();

// Session.

Transaction tx =Null;

Try{

// Start the transaction

Tx = session. beginTransaction ();

UserModel userModel =NewUserModel ("003", "morris", 22 );

// UserModel is instantaneous at this time

// Save the object

Session. save (userModel );

// UserModel persistent state at this time

// Submit the transaction

Tx. commit ();

}Catch(Effectione ){

E. printStackTrace ();

If(Tx! =Null){

Tx. rollback ();

}

}Finally{

Session. close ();

}

// At this time, the userModel is out of control.

1.2. Add a Persistent Object

? Persist () makes a temporary instance persistent. However, it does not guarantee that the Identifier value is immediately assigned to the persistent instance, which will occur during the flush process. Persist () also ensures that it does not execute the INSERT statement when the transaction boundary is called out. This is useful for long-running sessions with extended sessions/persistent context.

? Save () ensures that an identifier is returned. If you need to run INSERT to obtain the identifier (such as "identity" rather than "sequence" generator), this INSERT will be executed immediately, whether inside or outside the transaction. This may cause problems for long-running sessions with extended sessions/persistent context.

1.3. Delete A Persistent Object

? Delete () is used to delete an object. A parameter is an object and is not a primary key. When executing the delete method, the system first searches the database for records corresponding to the primary keys without objects, if yes, the deletion operation will be performed;

If not, no error is reported.

Hibernate: select usermodel _. userId, usermodel _. userName as userName2_0 _, usermodel _. userAge as userAge3_0 _ from userInfo usermodel _ where usermodel _. userId =?

Hibernate: delete from userInfo where userId =?

1.4. Modify A Persistent Object

? Update

Hibernate: update userInfo set userName = ?, UserAge =? Where userId =?

? Merger

L if the data in the database is consistent with the object data, execute the following SQL statement

Hibernate: select usermodel0 _. userId as userId1_0_0 _, usermodel0 _. userName as userName2_0_0 _, usermodel0 _. userAge as userAge3_0_0 _ from userInfo usermodel0 _ where usermodel0 _. userId =?

L if the database data is inconsistent with the object data, the following SQL statement will be executed

Hibernate: select usermodel0 _. userId as userId1_0_0 _, usermodel0 _. userName as userName2_0_0 _, usermodel0 _. userAge as userAge3_0_0 _ from userInfo usermodel0 _ where usermodel0 _. userId =?

Hibernate: update userInfo set userName = ?, UserAge =? Where userId =?

L if this record does not exist in the Database, add

Hibernate: select usermodel0 _. userId as userId1_0_0 _, usermodel0 _. userName as userName2_0_0 _, usermodel0 _. userAge as userAge3_0_0 _ from userInfo usermodel0 _ where usermodel0 _. userId =?

Hibernate: insert into userInfo (userName, userAge, userId) values (?, ?, ?)

1) if the session contains instances with the same persistence identifier, use the object state provided by the user to overwrite the old persistent instance.

2) If the session does not have a persistent instance, try to load it from the database or create a new persistent instance.

3) Finally, the persistent instance is returned.

4) The object provided by the user is not associated with the session, and it is still out of management.

? SaveOrUpdate is automatically detected. If it is a new record, it is added. If it is a change record, it is modified.

1) if the object has been persisted in this session, do not do anything

2) if another object associated with this session has the same persistent identifier, an exception is thrown.

3) if the object does not have a persistent identity attribute, call save ()

4) if the persistent identifier of an object indicates that it is a new instantiated object, save () is called for it ().

1.4.1. Differences between update and merge Methods

1) if the record you want to modify exists in the Database, update directly executes the modification statement each time. merge first searches for the record in the cache and no data exists in the cache, go to the database to query and then merge the data. If the data is the same, the merge method will not modify the data. If the data is different, merge will actually modify the database.

2) If the record you want to modify does not exist in the Database, update reports an error, while the merge method adds a new value to the database.

3) After update, the incoming TO object is PO, and merge is still.

4) if you are sure that the current session does not contain a persistent instance with the same persistence identifier, use update (). If you want to merge changes at any time without considering the session status, use merge (). In other words, in a new session, the first update () method is usually called to ensure that the operations on the re-join and unmanaged objects are first executed.

5) Note: If you use update TO change a to po, you must execute the update SQL statement no matter whether the object is modified or not.

1.4.2. Use update () or saveOrUpdate ()

1) The program loads objects in the first session.

2) The object is passed to the presentation layer.

3) Some changes have been made to the object.

4) The object is returned to the business logic layer.

5) The program calls the update () method of the second session to persist these changes.

1.5. query persistent objects by primary key

1) load Method: when loading, first query the level-1 cache. If no value is found, a proxy object is created and returned. Only when used can the level-2 Cache be queried, if there is no data in the second-level cache, query the database. If there is no data in the database, leave the exception

2) get method: first check the cache. If no specific data exists in the cache, query the database. If no value exists in the Database, null is returned. In short, the get method is not used, get real data

1.5.1. Differences between get and load

1) The get () method returns the object class directly. If no data is found, null is returned. Load () returns an object proxy object (the current object can be automatically converted to an object). However, when a contemporary object is called, if no data exists, an org object will be thrown. hibernate. objectNotFoundException exception

2) load first goes to the cache (session cache/second-level cache) for query. If not, a proxy object is returned (not immediately found in the DB ), it is queried in DB only when this proxy object is used later. This is what we often say is that load supports lazy by default)

3. get is first queried in the cache (session cache/second-level cache). If not, query it in the DB (that is, issue the SQL statement immediately ). In short, if you are sure that the database has this object, load () will be used, and get () will be used if you are not sure (this is highly efficient)

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.