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.