Advantages and disadvantages of Hibernate and Its Optimization Methods

Source: Internet
Author: User
I. Advantages:

Hibernate is an open-source object relationship ing framework that encapsulates JDBC objects in a lightweight manner, so that Java programmers can use the object programming thinking to manipulate the database as they wish.

Hibernate can be used in any scenario where JDBC is used. It can be used in both Java client programs and Servlet/JSP web applications. The most revolutionary thing is that, hibernate can replace CMP in the J2EE architecture of application EJB to fulfill the task of data persistence.

Most development institutions often create independent data persistence layers. Once the underlying data structure changes, it will be very costly to modify the rest of the application to adapt to this change. Hibernate fills this gap in time and provides an easy-to-use and efficient object relationship ing framework for Java applications. Hibernate is a lightweight persistence framework with rich functions. Hibernate is an open-source relational object framework that encapsulates JDBC in a lightweight manner. This allows programmers to operate databases using the object programming thinking as they wish.

Hibernate can be used in any situation where JDBC is used, that is, it can be used in Java client programs or Servlet/JSP web applications. It is more revolutionary that CMP in J2EE applications can be replaced to fulfill the task of data persistence.

Most development organizations often create their own data persistence layers. Once the underlying data structure changes, it will take a lot of money to modify the rest to adapt to this change. Hibernate fills this gap in time, providing an easy-to-use and efficient relational object ing for Java. It is a lightweight persistent layer framework with rich functions.

Hibernate uses the Java reflection mechanism instead of bytecode enhancement programs for transparency. It has excellent performance because it is a lightweight framework and has excellent flexibility in ing. It supports various relational databases, from one-to-one to many-to-many complex relationships.

Missing: it limits the object model you are using. (

Optimization:

Many people think that hibernate is inherently inefficient. Indeed, in general, the efficiency of hibernate that needs to be converted into SQL statements is lower than that of direct JDBC access. However, after a good performance optimization, the performance of Hibernate is quite satisfactory, especially after the second-level cache of the application, it can even achieve better performance of JDBC that does not use the cache, the following describes some common hibernate optimization strategies:
1. Capture Optimization
Crawling refers to how hibernate navigate between associations and how hibernate acquires the associated Object Policy. It mainly defines two aspects: how to capture and when to capture
1) how to capture.
Hibernate3 is mainly applied to object-to-one, one-to-one, and Object-join set (set, map, and so on ), four variants in total
Join crawling: You can use outer join in a select statement to obtain the associated instance or set of objects)
Select Capture: an additional SELECT statement is sent to capture the associated entities and sets of the current object.
In my development experience, the performance optimization here is relatively limited, and it is not worth too much attention.
Example:
A. apply to object-associated instances (default value: false)

B. apply to the object association set (Auto by default)

....

2) When to capture
It mainly includes delayed loading and instant capturing. By default, hibernate3 uses delayed loading for object associations, and common attributes use instant capturing. Through delayed loading and appropriate capturing granularity, performance can be improved by several times compared to optimization not used.
Capture now: when capturing a host object, capture its associated objects, associated sets, and attributes at the same time.
Delayed loading: when capturing a host object, it does not capture its associated objects, but is loaded only when the object is called.
Example:
A. apply to object associated instances (delayed loading by default)

B. apply to object association set (delayed loading by default)

....

For delayed loading, you must note that the use of delayed objects must be performed before the session is closed. lazyinitalizationexception of Hibernate is often because delayed loading objects are used outside the session lifecycle. For web development, we can use the opensessioninview mode. When the request starts, the session is opened and the session is closed when the request response ends. However, when the opensessioninview mode is used, it should be noted that if the response time is relatively long (the service is complicated or the client is a low-speed network), occupying session resources (that is, database connection) for too long may cause resource depletion.
3) Capture Granularity
Capture granularity refers to the number of objects that are pre-loaded at a time when they are navigated between associations. The poor performance of the hibernate Program often lies in the absence of careful consideration on the capture granularity, when a list is loaded and each object in the list is navigated, n + 1 SQL statement query is often performed.
Example:
A. apply to object associated instances (default value: 1). Note that object associated instances are set on the associated objects, for example
Class user
{
Group G;
}
The capture granularity should be above the group configuration file. For details, see

...

There is no common value for this value. It depends on the situation. If the data in the joined table is small, it can be set to a smaller value (3-20, if it is large, you can set it to 30-50. Note that the higher the value, the better. When the value exceeds 50, the performance is not improved much, but the memory consumption is unnecessary.
For example:
List Users = query. List ();
If there are 20 users and the 20 users and their groups are traversed, if the batch-size (that is, batch-size = "1") is not set, the worst case is
1 + 20 SQL statements are required. If batch-size = "10" is set, only 1 + 2 SQL statements are required.
B. apply to object association set (default value: 1)

....

2. Secondary Cache
Hibernate caches data at two levels: A level-1 cache, which is performed at the session level, mainly object cache. The object is saved with its ID as the key and exists during the lifecycle of the session; the second-level cache is implemented at the sessionfactory level, including the object cache and query cache. The query cache stores the query results with the key as the query condition, and stores the results during the sessionfactory lifecycle. By default, Hibernate only enables level-1 caching. By correctly using level-2 caching, unexpected performance is often achieved.
1) object cache:
After capturing an object, hiberate caches it with the ID as the key. The following configuration can be used when an object with the same ID is captured next time.
Method 1: Configure on the cache object

Useage indicates the type of cache used, such as read-only cache and read/write cache. For more information, see the hibernate reference guide, some caches do not support read/write caching in hibernate implementation. For example, jbosscache is only a read-only cache in hibernate implementation. For details about the cache Implementation's support for cache types, refer to Org. hibernate. cache package
Regions indicates cache blocks. Most cache implementations usually block the cache. This part is optional. For details, see cache implementations.
Method 2: Configure in hibernate. cfg. xml

I think the second method is better and can be managed in a unified manner.
2) query Cache
When querying, save the query results with the query condition as the key. You need to configure the following:
A. Configure in hibernate. cfg. XML (enable query cache)

True (For the previous attribute names, see constants.
Org. hibernate. cfg. enviroment. use_query_cache)
B. Program
Query. setcacheable (true );
Query. setcacheregions (...);
It should be noted that the query cache should be more effective in combination with the object cache, because the query cache only caches the primary key data of the query result list.
Generally, during development, data that is relatively stable and frequently referenced, such as data dictionary, is cached in two levels, perform a second-level cache for queries that frequently change query conditions and query data. Because the second-level cache is in the memory, and the hibernate cache is not weekreference, do not place large pieces of data into it, otherwise, the memory may cause a great deal of pressure.
3. Batch Data Operations
When performing mass data operations (tens of thousands or even tens of millions), pay attention to the following two points: 1. Batch submission and 2. Clear unwanted level-1 cache data in a timely manner.
1) The so-called batch commit is to avoid frequent use of session flush. Every time the session is flush, Hibernate synchronizes the Po data in the database, it is a performance disaster for sea-level data operations (the difference between submitting thousands of pieces of data at the same time and flush one piece of data may be dozens of times the difference ). Generally, data operations are placed in transactions. When a transaction is committed, Hibernate automatically performs flush operations for you.
2) Clear unwanted level-1 cache data in a timely manner: hibernate uses a level-1 cache by default, and during the session's lifecycle, all data is captured and placed in the level-1 cache, when the data size is large, the data captured into the memory will put a lot of pressure on the memory. Generally, the data is operated in batches, and the first-level cache is cleared after an operation, such
Session. Clear (user. Class)
4. Miscellaneous
Dynamic-insert, dynamic-Update, dynamic insertion, and dynamic update means that only non-empty data is inserted when hibernate inserts data, and only changed data is modified when data is modified, for example
Class user
{
ID
Username
Password
}
If u. id = 1, U. username = "ayufox", U. password = NULL. If dynamic insert is not set, the SQL statement is insert into users (ID, username, password) values (1, 'ayufox ','), if this parameter is set, the SQL statement is insert into users (username) valeus ('ayufox ')
If u. password = '11', if dynamic update is not set, the SQL statement is update users set username = 'ayufox', password = '11' where id = 1, if set, update user SET Password = '11' where D = 1
The settings are in the ing file of the class, as shown below:

This setting has limited performance improvement.

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.