8.Hibernate Performance Optimization

Source: Internet
Author: User
Tags sessions

Performance optimization

1. Note the use of session.clear (), especially in the continuous paging

A) traversing a large set, traversing the MSG, and taking out the object containing the sensitive typeface

b) Another form of memory leak (//interview question: Is there a memory leak in Java?) The syntax level is not, but can be caused by Java, for example: The connection pool does not shut down, or IO does not close after reading)

2.1+n Questions (typical interview questions)

For example, when there is a many-to-one relationship, many of the parties by default are able to remove one side of the

Fetch=fetchtype.eager is the default in @ManyToOne

When a side of load is loaded, it will also load one of the parties, causing an unnecessary SQL statement to be executed

Workaround, the following:

A) @ManyToOne (Fetch=fetchtype.lazy)

When multiple-to-one (@ManyToOne) has set the property "Fetch=fetchtype.lazy"

Only when needed (for example: T.getcategory (). GetName ()) to get the data in the associated table can solve the n+1 problem

b) @BatchSize

Add @batchsize (size=5) to the header of the table class (in this case, category) associated with the query table (in this case, the topic Class)

Indicates that 5 records can be detected each time thus reducing the number of SELECT statements

c) Join Fetch

Modify the HQL statement as--"from Topic T left join fetch t.category C

D) QBC

The principle is the same as the one above, and using QBC's Createcriteria (*.class) to perform queries can also avoid n+1 problems

  

3.list and iterate differences (//mainly for interview)

A) list takes out all the data in the table to form an object

b) Iterate first take the ID, and so on, then use the ID to take the object

c) The second time the list is issued in the session, still back to the database query

d) Iterate the second time, will first find the session cache

Hibernate caching mechanism

The three states of the persisted object in the preceding hibernate are mentioned, and the flag of the object in the persistent state is the object in the cache.

The cache is similar to a key-value pair, key is ID, and then value is the cached object

When you want to read and write to the object, the cache is checked first,

/* level cache and level two cache and query cache */

First-level cache: Session cache, each session has its own session cache, session cache of different sessions cannot be shared

Second level cache: Sessionfactory level cache, all sessions can access level two cache

Query cache: The same SQL statement executes only once

When the cached object 1. Frequently accessed 2. Does not change frequently 3. Using a two-level cache when the number is small

Open Level Two cache (two steps):

1. Set in Hibernate.cfg.xml:

1         <property name= "Cache.use_second_level_cache" >true</property>2         <property Name= "Cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>

[Email protected] annotations (provided by hibernate extension)

@Cache (Usage=cacheconcurrencystrategy.read_write)

(A level Two cache is turned on for a class, and a two cache is created for read-write operations on objects of that class)

Note: Using Ehcache level two cache requires importing Ehcache-1.2.3.jar and Commons-logging-1.0.4.jar packages

 Note: 

1.load uses a level two cache by default, and iterate uses a level two cache by default

2.list defaults to level two cache plus data, but does not use when querying

This means: Session.createquery ("from Category"). List (); The data will be added to the cache, but will not be queried in the cache.

  3. You can use <property name= "Hibernate.cache.use_query_cache" >true</property> to open the query cache, which is off by default,

Query cache to identify a query using the cache, when executing the same SQL statement, will not go to the database to find, but also from the cache to find the statement

After you open the query cache, be aware that the call to Query.list () operation must be displayed before calling Query.setcacheable (true)

Example: Session.createquery ("from Category"). Setcacheable (True). List ();

Note: The query cache only works on Query.list (), Query.iterate does not work, that is, Query.iterate does not use

  

4. Cache algorithm (new cache object to come in, how to replace): (interview)

LRU LFU FIFO

1.Least recently used recently least used replaced

2.Least frequently used is replaced with the lowest frequency ratio

3.First in first out replaced sequentially

Configuring Memorystoreevictionpolicy= "LRU" in Ehcache.xml

Transaction concurrency Processing

A) transaction: ACID
Atomic Consistency Itegrity Durability

b) Issues that may occur when a transaction is concurrent:

1. Dirty Read (read the data that another transaction has not yet committed in the process)

2. Non-repeatable read (during the execution of transaction A, transaction B is opened, the data in the column is modified and submitted,

Results in inconsistent data read by transaction A before transaction B is executed and after transaction B is executed)

3. Virtual read (when querying the data of a certain condition, when the query is started, someone else joins or deletes some data, and then reads it differently from the original data.

Similar to non-repeatable reads, but not repeatable reading of the data in the column, and Phantom reading is for the whole column of additions and deletions)

c) Isolation level of database transactions

1------read-uncommitted

2------read-committed

4------REPEATABLE READ

8------Serializable

The preceding number is the number corresponding to the transaction isolation level of Hibernate

Why use 1 2 4 8 instead of 1 2 3 4

1=0000 2=0010 4=0100 8 = 1000-bit operation high efficiency

  

Read-uncommitted (allow read uncommitted data) will appear dirty Read, phantom-read, non-repeatable read problem

Read-commited (this is typically used in read-committed data items) does not appear dirty read,

Because only another transaction commit will read the results, but will still appear non-repeatable read and Phantom-read

/* Use the read-commited mechanism to resolve non-repeatable read and phantom-read issues using pessimistic lock optimistic locks */

Repeatable read (Other transactions in transaction execution cannot perform modification or insert operation is more secure)

Serializable solve all problems (sequential transaction not concurrency, rarely used in practice)

How to set the transaction isolation level for hibernate (using the Hibernate.connection.isolation configuration for values 1, 2, 4, 8)

1.hibernate.connection.isolation = 2 (if you do not set the default dependency level of the database itself)

2. Use pessimistic lock to resolve repeatable read problem (dependent on database lock (SELECT ... for update))

Hibernate uses load for pessimistic lock and lock Session.load (Inventory.class, 1, Lockmode.upgrade); When a SELECT statement is generated, a pessimistic lock is added for the for update

A) Lockmode.none lock-free mechanism, switch to this mode when transaction ends

b) Lockmode.read will automatically acquire the lock during the inquiry

c) Lockmode.write insert update Hibernate acquires the lock automatically

D) The above 3 types of lock modes are used internally by hibernate (no need to set)

E) lockmode.upgrade_nowait is the way that ORACLE supports locks

3. Optimistic lock (not actually a lock, is a conflict detection mechanism)

Add the Version attribute to the entity class (the database will also generate the field with the initial value of 0) and add @Version annotations before its Get method

When the row data is updated every time during the operation, the version value is added by 1 to determine whether the data was modified by another transaction before the transaction commits.

(When committing a transaction, by comparing the in-memory version value and the version value in the database)

Note: The difference between optimism and pessimism:

1. Pessimistic lock more pessimistic, think there will be concurrency situation, so in advance a lock,

2. Optimistic lock more optimistic, not anxious to lock, but first to determine whether there is a situation of concurrent access, if there is, and then do the corresponding treatment

          

8.Hibernate Performance Optimization

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.