N + 1 is actually called 1 + N.

Source: Internet
Author: User

When you use tools such as hibernate or ibatis to query a database, N results may be queried due to cache or lazyload, you only need to query SQL once, but you have to perform more than 1 N database queries, resulting in low efficiency.

1: When iterate is used for query

Query q = session. createquery ("from user ");

List L = Q. iterator (); // at this time, an SQL statement select user_id from user is executed, and only the user ID value is obtained.

Iterator <user> it = L. iterator ();

While (it. hasnext ()){

System. Out. println (it. Next (); // when you are about to obtain the result, Hibernate will query the result one by one based on the ID value.

// Search, first in the first-level cache, then in the second-level cache, and finally in the database

// Query. If the cache is not hit, 1 + N queries are generated.

}

2: When querying sub-objects

For example, first query a person's ID card, "From idcard where card. id = "111"; if you want to get the person object, use idcard. the getperson method, which queries the database again. This results in 1 + N queries due to lazy loading. By default, Hibernate enables lazy loading. That is to say, if the attached object is loaded, the primary object will not be automatically loaded.

3: the query cache is opened, but the time setting is unreasonable.

Solution:

1. make rational use of the second-level cache

2. Pay attention to the method when setting lazy loading.

N + 1 is actually called 1 + N.

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.