Hibernate caching mechanism and transaction isolation mechanism

Source: Internet
Author: User

First level cache (session cache)

} First- level cache Management

? The application calls the session's save (), update (), Saveorupdate (), get () or load (), and the list (), iterate () that invokes the query interface, if the corresponding object does not exist in the session cache. Hibernate will add the object to the first level cache.

? Cache can be emptied via close/clear/evict

} function

Because the lifetime of the session is often very short, the first level of the cache that exists within the session is of course very short, so the hit rate of the first level cache is very low. The improvement of the system performance is also very limited. The main function of the session internal cache is to keep the session internal data state synchronized.

Second-level cache (Sessionfactory cache)

Open

? <property name="Hibernate.cache.use_second_level_cache" >true</property>

? <property name="Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>

} How to use:

? Class definition before: @cache, the object of that class is put in level two cache.
@Cache (usage=cacheconcurrencystrategy. Read_write)// into the level two cache can also be modified. It is generally used.

} What content is placed in Level two cache:

? frequently accessed, infrequently altered, and limited in number.

Get/load will use level two cache.

} Iterate also uses level two caching.

The list defaults to the level two cache, where the results detected by list are placed in a level two cache. However, the list itself does not use a level two cache when querying.

Various level two cache plugins

Query cache

the query cache only works on query.list ()

the query cache relies on a level two cache, so be sure to turn on level two caching.

The query cache implementation mechanism: With the query statement as key, the ID of the object found is value

the configuration and use of the query cache:

? Turn on level two caching

? <propertyname= "Hibernate.cache.use_query_cache" >true</property>//default is Fasle

? The query cache must be enabled manually in the program, such as: Query.setcacheable (TRUE);

Caching algorithm Issues

After the cache is full, clear out which object in memory.

? Lru

? Least recently used was least recently used. Each cached object records a last-used time.

? LFU

? Least frequently used has the least recently used frequency.

? Fifo

? First In First out

1+n problems

In a one-to-many/many pair, there are often 1+n problems.

? In 1 parties, find n objects, and then need to have n objects associated with the collection, so that an original SQL query into a n+1 bar.

} Solution:

? lazy Loading ( delayed loading, lazy loading )

? @OneToMany (mappedby= "Banji", Fetch=fetchtype. LAZY) ( This is the default)

? Level Two cache

? When object updates, deletions, and additions are much less than the query, the two-level cache application will not be afraid of n+1 problems, because even if the first query is slow, then the direct cache hit is fast, just as the n+1 is used.

List and iterator differences

The list will only populate the level two cache, but it cannot take advantage of the level two cache.

Iterator can read the level two cache, for a query statement, it will first find all eligible records from the database ID, and then through the ID to cache find, for the cache does not have records, and then construct the statement from the database. No hits in the cache, less efficiency.

The best way to do this is:

? Use list when the app starts and when the data is modified. usually use iterator. (only for infrequently modified data!) )

The selection of caching mechanism

} Generally start development and do not use caching mechanisms.

If performance requirements are not met on demand, the cache is increased.

? Second-level cache: The content of the cache data content changes less frequently.

? Query cache

Many systems often add caches at the application level:

? Application of Oscache in the Java EE

Data batch Processing

Recommendations

? Processing of large quantities of data do not use Hibernate, giving priority to JDBC batch processing. (JDBC is generally used)

? If the performance requirements are extremely high, consider PL/SQL

Transaction ISOLATION LEVEL

Transaction Basic Concepts

Acid is the initials of atomicity (atomicity), consistency (consistency), isolation (isolation), and durability (persistence)

? Atomicity means that all operations within a transaction are a whole, either all successful or all fail;

? Consistency means that when one operation fails within a transaction, all changed data must be rolled back to the pre-modified state;

? Isolation: The state in which the data is located when the transaction views the data, either when another concurrent transaction modifies its state, or after another transaction modifies it, and the transaction does not view the data in the middle state.

? After the persistence transaction completes, its effect on the system is permanent.

The transaction isolation level is low to High:

? READ UNCOMMITTED (readuncommitted)

? Read Committed (readcommitted)

? Repeatable Read (RepeatableRead)

? Serialization (Serializable)

} Read UNCOMMITTED (readuncommitted)

? This is the lowest transaction isolation level, the read transaction does not block read and write transactions, and the write transaction does not block the read transaction, but it blocks the write transaction.

? Write transactions do not block read transactions, can read uncommitted data, easily cause dirty reads

? Dirty Read phenomenon:

? Dirty Read Solution:

? If any other transaction cannot read its modified value before the first transaction commits, the problem can be avoided.

? Read Committed (readcommitted)

? A write transaction blocks read and write transactions, but read transactions do not block read and write transactions. A read transaction does not block a write transaction, but it is possible to make it non-repeatable (in the same transaction, when the data is read again "is your select operation", the data is read, and the data read for the 1th time is different.) The result of the query will be indeterminate).

? Non-repeatable READ solution:

? Lock up records that have been queried! Do not allow other things to write operations

? Repeatable Read (RepeatableRead)

? Read transactions block write transactions , but read transactions do not block read transactions , and write transactions block write transactions and read transactions.

? Read transactions do not block read transactions (for records, not tables), which can cause phantom read problems

? Magic Reading Solution:

? The workaround is to lock the table so that the record that produces the phantom reads is inserted or deleted.

? However, the illusion of reading is generally not considered.

? Serialization (Serializable)

? This isolation level is the most stringent isolation level, and if set to this level, then all the above problems (dirty read, non-repeatable read, Phantom Read) will not occur.

? Very low performance, generally do not use!

We generally use the Read committed or lower transaction isolation level, with a variety of concurrent access control policies to achieve the purpose of concurrent transaction control.

} How to use:

<!--establish transaction ISOLATION level: 1,2,4,8. Binary: 0001, 0010,0100,1000. This can be done directly using bit arithmetic. Bits operations are often used in privilege control--

<propertyname="Hibernate.connection.isolation" >2</property>

Optimistic lock and pessimistic lock

} optimistic lock optimisticlocking

? As the name implies is to maintain an optimistic attitude, we believe that the system of transaction concurrency update is not very frequent, even if the conflict is OK, the big deal again.

? The basic idea is that every time a transactional update is committed, we want to see if something has been modified since the last time it was read, and if it has been modified, the update will fail.

? Common Implementation methods:

? Add a version control field to our entity that will be versioned each time a transaction is updated field: The value of the Version field is plus 1.

? add @version,private int Version to the entity class ; Getset can be.

} Pessimistic lock pessimisticlocking

? The basic idea is that every time a transaction reads a record, it locks the record so that other transactions are updated and must wait for the previous transaction to commit or rollback the unlock.

? Pessimistic lock implementation, often rely on the database provided by the lock mechanism (also only the database layer provides a lock mechanism to truly guarantee the exclusivity of data access, otherwise, even in the system to implement the locking mechanism, there is no guarantee that the external system will not modify the data)

Comparison of optimistic and pessimistic locks:

} Optimistic Lock:

? Advantages: Good concurrency, high performance.

? Disadvantage: The user experience is not good, entered a half-day, submitted to be informed that has been modified!

}

} Pessimistic Lock:

? Advantage: The record will be locked, and no other user can manipulate the record until a user has finished modifying it.

? Disadvantage: Concurrency is not good, performance is not high.

A pessimistic lock is more likely to be concurrency-oriented, and it is generally sufficient to use optimistic locking in our applications.

Hibernate caching mechanism and transaction isolation mechanism

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.