Hibernate learning-(iv) three states in session and life cycle

Source: Internet
Author: User
Tags commit flush

The session interface is the most important interface that hibernate provides to the application to manipulate the database, providing basic saving, updating, deleting, and loading (not "querying"). ) method of the Java object.

The session has a cache, and objects in the cache are called persisted objects, which correspond to related records in the database. Session can be followed at some point in time

Changes to the stored object to execute the associated SQL statement to synchronize the update database. Standing in the perspective of persistence, hibernate divides objects into 3 states: Transient,

Persistent, Detached. The specific method of the session enables the object to be from one state to another.

The implementation of the session collection contains a series of Java collections that form the session cache, as long as the session instance does not have an end-of-life cycle,

And the cache is not cleaned, the objects placed in the cache do not end the life cycle. This first-level cache of Hibernate reduces Hibernate application access to data

The frequency of the library.

There are several ways to manipulate the session cache :

Flush (): Keeps the records in the data table consistent with the state of the objects in the session cache, and in order to remain consistent, the corresponding SQL statement may be sent

1, in the transaction commit () method, first call the session's flush () method, and then commit the transaction.

2. The flush () method may send an SQL statement, but the transaction will not be committed.

Refresh (): The SELECT statement is forcibly sent to keep the state of the object in the session cache consistent with the corresponding record in the data table. In the use of this method, you will encounter

The issue of transaction isolation, which is described later in detail.

Clear (): Cleans up the cache. The contents of the cache are emptied.


In front of the stand in the perspective of persistence, hibernate divides the object into 3 states: Transient, Persistent, Detached. The specific method of the session can make the

Like from one state to another state.


The main difference between the three states is that:a> has no ID b>id in the database and there is no c>id in the session cache.

Transient: Just new out of the object, the session cache and the database are not;

Persistent:session cache and database exist, have ID;

The detached:session has ended, so the session cache does not exist, and the database exists.

Introduction Method ************************************* ************************

Save (): transforms the temporary object into a persisted object, assigns an ID to the object, and sets the ID to be invalid before the Save method (if an ID generation policy is set), the persisted object

The ID cannot be modified.


persist (): The function is the same as save, but there is no guarantee that the identifier is immediately populated into the persisted instance, and that the fill in the identifier may be deferred to flush (). But it

Ensures that an insert event is not triggered immediately when it is called outside of a transaction, and the Save method immediately returns an Insert event, whether inside or outside the transaction

Department.


get (): The object is immediately loaded, which is immediately retrieved.


load (): The object can also be loaded, but deferred, and if the object is not used, the query operation is not performed immediately, but instead an intermediary proxy object is returned. If the number

There is no data in the table where the Get method returns NULL, and the load method throws an exception (but if the object is not used, it is simply load and does not report an exception). Because of the load

Lazy load feature, if you turn the session off before you actually use it, a lazyinitializationexception will be thrown.


Update (): You can update the transient and detached objects, change them to persistent state, and update their contents (send an UPDATE statement). Simply update a

The non-primary key property of the Transient object returns an error (because executing the UPDATE statement needs to know its ID to execute), but if the transient object

If you set a primary key directly, you can perform an update, and you need to explicitly invoke an UPDATE statement. If you are updating the value in the detached state, you can load the object directly after the

With the Set method, and you do not need to explicitly call the Update method, because the flush () method executes itself when a transaction commits (if there is no actual update at this time, it will not execute

UPDATE statement).

The above Update method will iterate through all the fields in a single update, and if a field has a lot of content, it will seriously affect the efficiency, so the following

Several solutions:

Set the property tag's Update property in ①xml or set the updatable attribute to False in @column (use less because it is very inflexible)

The Dynamic-update property of the set class in ②xml is false. However, this method is not used in the annotation declaration.

③ uses the merge () method (but actually adds a single SELECT statement, which is less cost-effective)

④ using HQL statements (recommended)


Delete (): performs a delete operation, as long as the primary key corresponds, a DELETE statement is submitted when the transaction commits or the flush cache. If there is no corresponding primary key, the party

An exception is thrown by the method. (You can perform a delete operation as long as you have a primary key)


saveorupdate: for a transient object, which is equivalent to the Save method, an INSERT statement is executed; for persistent or detached objects, it is quite

Update method, an UPDATE statement is executed.


Clear (): clear Session cache.


flush (): forces the content in the cache to synchronize with the contents of the database





PS: Transaction-related knowledge record:

Features of the "Transaction": "A.c.i.d." ===>atomicity, consistency, isolation, durability (atomicity, consistency, isolation, durability)

For multiple transactions running concurrently, when these access the same data in the database, if the necessary isolation mechanism is not taken, it can cause various concurrency problems:

Dirty read: also known as invalid data readout, refers to the database access, transaction T1 a value modification, and then the transaction T2 read the value, and then T1 for some reason to revoke the value

Changes, which results in invalid data being read by T2.

non-repeatable read: means that in database access, two identical queries within a transaction range return different data. This is due to the modification of other transactions in the system at query time.

caused by a hand. For example, a transaction T1 read a data, the transaction T2 read and modify the data, T1 in order to examine the read value and read the data again, then got

Different results.

Phantom reads: a phenomenon that occurs when a transaction is not executed independently, such as when the first transaction modifies data in a table, such as a change involving the "full

Data Line ". At the same time, the second transaction modifies the data in the table by inserting a "new row of data" into the table. Then the operation will occur in the first

The user of the transaction finds that there are no modified rows of data in the table, as if the illusion had occurred.

Transaction ISOLATION Level:

Read_uncommitted (1): Dirty reads are allowed, but updates are not allowed to be lost. If a transaction has already started writing data, the other transaction is not allowed to enter the

Write operations, but allows other transactions to read this line of data.

Read_committed (2): Allow non-repeatable reads, but dirty reads are not allowed. A transaction that reads data allows other transactions to continue to access the row's data, but does not commit

The write transaction will prohibit other transactions from accessing the row.

Repetable_read (4): Disables non-repeatable reads and dirty reads, but does not completely avoid phantom read data. A transaction that reads data will prohibit the write transaction (but allows

Read transactions), and write transactions prohibit any other transaction.

Serializeable (8): Provides strict transaction isolation. It requires the transaction to serialize execution, the transaction can only be executed one after another, and cannot be executed concurrently.

The JDBC database connection uses the default isolation level of the database, where the isolation level can be explicitly set in Hibernate's configuration file, and each isolation level corresponds to a

An integer (such as the number in parentheses next to the four English names above). Set the method to include in Hibernate.cfg.xml:

<property name= "connection.isolation" >[Isolation level number]</property>



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.