CRUD Operations for Hibernate objects

Source: Internet
Author: User

1. CRUD Operations for Hibernate objects 1.1. Three states of an object

Instantaneous (Transient)-the object created by the new operator and not yet associated with the hibernatesession is considered instantaneous (Transient). Instantaneous (Transient) objects are not persisted to the database and are not given persistent identities (identifier). If an instantaneous (Transient) object is not referenced in the program, it is destroyed by the garbage collector (garbage collector). Hibernate session can be used to change it to a persistent (persistent) state. (Hibernate will automatically execute the necessary SQL statements)

Persistent (persistent)-persistent (persistent) instances have corresponding records in the database and have a persistent identity (identifier). An instance of persistence (persistent) may have just been saved, or just loaded, regardless of which, by definition, it exists in the context of the associated session. Hibernate detects any changes to an object that is in a persistent (persistent) State and synchronizes the object data (state) with the database (synchronize) when the current operating unit (unit of work) finishes executing. Developers do not need to perform update manually. Changing an object from a persistent (persistent) state to an instantaneous (Transient) state also does not require that the DELETE statement be executed manually.

Off-Tube (Detached) – When the session associated with a persistent (persistent) object is closed, the object becomes off-pipe (Detached). The reference to the Detached object is still valid and the object can continue to be modified. If the Detached object is re-associated to a new session, it will be converted again to persistent (persistent) (changes in the Detached will be persisted to the database). This feature makes it possible for a programming model to be programmed with a long-running operating unit (unit of work) in which the user thinks time is think-time. We call it an application transaction, that is, from the user's point of view, an operating unit (unit of work).

// read the configuration file and get Configuration Object

Configuration Config = new configuration (). Configure ();

// get a session factory

Sessionfactory SF = config. buildsessionfactory ();

Session Session = SF. opensession ();

SF. getcurrentsession ();

//session.

Transaction tx = null;

Try {

// Start a transaction

TX = session. BeginTransaction ();

Usermodel Usermodel =new Usermodel ("003","Morris", 22);

// at this Usermodel for instantaneous State

// Save Object

session. Save (Usermodel);

// at this Usermodel Persistent State

// Commit a transaction

TX. commit ();

} Catch (Exceptione) {

e. Printstacktrace ();

if (tx ! =null) {

TX. Rollback ();

}

} finally {

session. Close ();

}

// at this Usermodel off-pipe State

1.2. Add Persistent objects

? Persist () causes a temporary instance to persist. However, it does not guarantee that the identifier value is immediately assigned to the persistence instance, which occurs at flush. Persist () also guarantees that it does not execute an INSERT statement when it is out of the transaction boundary. This is useful for long-running sessions with extended session/persistence contexts.

? Save () guarantees that an identifier is returned. If you need to run insert to get an identifier (such as "identity" rather than the "sequence" generator), the insert will execute immediately, whether you are inside or outside the transaction. This can be problematic for long-running sessions with extended session/persistence contexts.

1.3. Delete Persistent objects

? Delete () is used to remove an object, the parameter is an object, not a primary key, the execution of the Delete method will first go to the database to find there is no object's primary key corresponding to the record, if there is a delete operation;

If not, there will be no error.

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. Modifying Persistent objects

? Update

Hibernate:update userInfo set username=?, userage=? where userid=?

? Merger

If the data in the database is consistent with the object's 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=?

If the database data is inconsistent with the object's data, the following SQL statement is 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 an instance of the same persistence identity exists in the session, overwrite the old persisted instance with the state of the object given by the user

2) If there are no corresponding persistent instances in the session, try to load from the database or create a new persisted instance

3) Finally returns the persisted instance

4) The user given this object is not linked to the session, it is still off the tube

? Saveorupdate automatic detection, if it is a new record to add, if it is to modify the record, modify

1) If the object is already persisted in this session, do nothing

2) If another object associated with this session has the same persistent identity, throw an exception

3) If the object does not persist the IDENTITY property, call Save () on it

4) If the persistent identity of the object indicates that it is a newly instantiated object, call Save () on it.

1.4.1. Differences between the update and merge methods

1) If the database contains the records you want to modify, update each time is directly execute the modification statement, and the merge is to find in the cache, the cache does not have the corresponding data, to the database to query, and then merge the data, if the data is the same, then the merge method will not be modified, If the data has a different location, the merge will actually modify the database.

2) If the record you want to modify does not exist in the database, update is an error, and the merge method is treated as a new value, adding a new data to the database.

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

4) If you are sure that the current session does not contain a persistent instance with the same persistent identity as it is, use Update (). If you want to merge changes at any time without considering the state of the session, use merge (). In other words, in a new session it is usually the first call to the update () method to ensure that the operation of the re-associated off-pipe object is executed first.

5) Note: When using update to change A to PO, the update SQL statement is executed regardless of whether the object is modified or not.

1.4.2. Scenes using update () or saveorupdate ()

1) The program loads an object in the first session

2) The object is passed to the presentation layer

3) The object has undergone some changes

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: Load when the first query primary cache, do not create and return a proxy object, wait until the use of time, only check the level two cache, if there is no data in the level two cache to check the database, if not in the database, throw exception

2) Get method: First check the cache, if the cache does not have this specific data, check the database, if the database has no value, return null, anyway get method no matter use, all need to get the real data

1.5.1. The difference between get and load

1) The Get () method returns the entity class directly and returns NULL if no data is found. Load () Returns an entity proxy object (currently this object can be automatically converted to an entity object), but when the proxy object is called, a Org.hibernate.ObjectNotFoundException exception is thrown if no data is present

2) Load first to cache (session cache/Level two cache) to check, if not return a proxy object (not immediately to the DB to find), and so on later use this proxy object operation, only to the DB query, this is what we often say load is supported by default lazy loading (lazy)

3. Get to cache (session cache/Level two cache) to check, if not on the DB to check (that is, the issue of SQL immediately). In short, if you are sure that the object is in db with load (), you are not sure to use Get () (This is high efficiency)

CRUD Operations for Hibernate objects

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.