hibernate optimization

Cache optimization:
           To optimize Hibernate, we must know where to optimize and where to start. Hibernate's optimization direction: database design, HQL optimization, caching, main configuration, lazy loading, method selection, collection selection, transaction control, batch operation


Specific analysis
The first point: database design

       The previous blog introduced database design, and today we also start from this At the beginning, the design of the watch is the foundation of building, how to make the foundation simple and strong is the most important.

Optimization strategy:

1. Build indexes

2. Reduce associations between tables

3. Simplify query fields, do not use useless fields, already control the returned results, and try to return a small amount

of data 4. Appropriate redundant data, but not too much High paradigm

The second point: HQL optimization




                                            (HQL knowledge graph)

     If you want to know more about the suggestions, take a look at this blog HQL detailed use, I personally think that the writing is OK, and the knowledge is summarized in detail.

Summary:

1. Entity query: You can use sql statement to query

2. Entity update and deletion: Hibernate3 provides a more flexible and efficient solution directly

3. Attribute query: Dynamically construct instance objects and encapsulate the result set

4. Grouping and Sorting:

A. Order by clause

B. Group by clause and statistical query

C. Optimize statistical query: inner join, outer join

5. Parameter binding: Like jdbc, it provides rich support for hibernate parameter binding.

The third point: cache

Operation mechanism:

between the application and the physical data source, its role is to reduce the frequency of the application's access to the physical data source, thereby improving the running performance.

Caching is widely used to optimize databases. When some data is read from the database, we can put them in the cache. In this way, we can directly take it out of the cache when we use it again, so that our efficiency is much improved.
Scope of control:

The first-level cache is a database transaction or an application transaction that usually corresponds to the life cycle of the session object. It is a cache within the transaction scope. The second-

level cache is a pluggable cache plug-in, which is managed by the SessionFactory. Since the life cycle of the SessionFactory object corresponds to the entire process of the application, the second-level cache is a city-wide or cluster-wide cache. Used to initialize data that rarely changes, data that is not important, data that will not be accessed concurrently.



Some issues and suggestions for Hibernate caching: Hibernate's caching Point

4 : Capture strategy

1. Capture optimization: Hibernate navigates between associations, making full use of the technology provided by Hibernate

2. How to capture

Immediate capture: when to capture When the host object is fetched, its related objects and association sets and attributes are captured at the same time.

Lazy loading: when fetching the host object, the associated object is not captured, but is loaded when the object is called.

3. Capture granularity: set the number of captures Point

5 : Batch data processing (modification and deletion)

In Hibernate2, if you need to modify or delete any data, you need to perform a query operation first, and then modify and delete after getting the data.

1. Instead of using the Hibernate API, you can directly use the JDBC API to query the original SQL statement. This method is better and relatively faster.

2. Use stored procedures

3. The hibernate API can be used within a certain range, but not for very large data volumes.

The sixth point: the use of the

     result set: the use of the result set: the difference between list() and iterator()

Query method:

list can only use the query cache (but the query cache has little effect in the trading system), and cannot use the second-level cache. The single entity of the list, but the objects detected by the list will be written to the second-level cache, but it generally only generates fewer SQL statements, and in many cases it is one.

The iterator uses the second-level cache. For a query statement, it will first find the IDs of all eligible records from the database, and then go to the cache to find them through the ID. One execution will generate N+1 SQL statements.

Result:

The use of list may overflow.

Through Iterator, combined with the cache management API, the memory problem can be well solved in massive data query.

Comprehensive consideration:

Generally, List will fill the second-level cache, but it cannot use the second-level cache. The Iterator can read the second-level cache, but if it cannot be hit, the efficiency is very inefficient. The general processing method is to use the list for the first query, and then use the iterator to query.

Summarize


Hibernate optimization summary and main configuration, method selection, and transaction control are not involved, because these aspects are relatively simple, but they are still very important.

When implementing a project, we don't need to think about these problems. When doing a project, the first step is to run, and the second step is to optimize it. In many small projects, the second step is generally not done, so when we do the project, we still have to keep in mind to run it. If we are doing research or the problem is serious, we will consider optimization.

In terms of Hibernate tuning, there is no best, only better. Let us continue to actively find optimization methods to optimize our programs and ourselves.

Regarding Hibernate optimization, I hope you will leave valuable comments and communicate with each other!






1. Reduce the frequency of accessing the database and reduce the number of select statements. The implementation methods are: use urgent left outer join or urgent inner join; delay retrieval or immediate Retrieval sets the number of batch retrievals; use the query cache.

  2. Avoid loading redundant data that the application does not need to access. The implementation methods include: using the lazy loading strategy; using collection filtering.

  3. To avoid the report query data occupying the cache, the realization method is to use the projection query function to query some attributes of the entity.

  4. Reduce the fields in the select statement, thereby reducing the amount of data to access the database. The method is to use the iterate() method of Query.

  The iterate() method of Query first retrieves the ID field, and then searches for the matching Customer object in the first-level cache and the second-level cache of hibernate according to the ID field. If it exists, it is directly added to the query result set, otherwise it is executed. Additional select statement to retrieve the object from the database based on the ID field.
Query query = session.createQuery("from Customer where age<30");  
 
  Iterator result = query.iterate(); 
Query query = session.createQuery("from Customer where age<30");

  Iterator result = query.iterate();


For frequently used query statements, if query caching is enabled, when the first When a query statement is executed once, hibernate will store the query result in the second-level cache, and when the query statement is executed again in the future, it only needs to obtain the query result from the cache, thereby improving the query performance. If the query result contains entities, the second-level cache will only store the OID of the entity, while for projection queries, the second-level cache will store all data values.

  The query cache is suitable for the following occasions: query statements that are frequently used when the application is running; rarely insert, delete, and update the database data associated with the query statement.

  The steps for enabling query caching for query statements are as follows:

  1. Configure the second-level cache.

  2. Set the query cache property in the hibernate configuration file: hibernate.cache.use_query_cache=true

  3. Even if the cache is set, the query cache will not be enabled when the query statement is executed, it will only be enabled after calling query.setCacheable() Cache:



Query query = session.createQuery("from Customer c where c.age > :age");  
 
  query.setInteger("age", age):  
 
  query.setCacheable(true); 

 If you want to control the query cache more granularly, you can set the cache region: query.setCacheRegion("customerQueries");

  hibernate provides 3 query-related cache regions:

  1. The default query cache region: net.sf.hibernate. cache.StandardQueryCache.

  2. User-defined query cache area: such as customerQueries.
///Enable the timestamp, or mark it with @version in the entity to prevent multiple clients from operating the same record at the same time
  . 3. Timestamp cache area: net.sf.hibernate.cache.UpdateTimestampCache.

  Both the default query cache area and the user-defined query cache area are used to store query results, and the timestamp cache area stores the timestamps of insert, update, and delete operations on tables related to query results. Hibernate uses the timestamp cache area to determine whether the cached query results are expired. When the application process makes changes to the relevant data in the database, hibernate will automatically refresh the cached query results. However, if other application processes modify the relevant data of the database, hibernate cannot monitor this change. At this time, the application must be responsible for monitoring the change (such as by sending and receiving events or message mechanisms), and then manually refresh the query results. .

  The Query.setForceCacheRefresh(true) method allows to manually refresh the query results, which makes hibernate discard the existing query results in the query cache area, re-query data in the database, and then store the query results in the query cache area.



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042233&siteId=291194637