search
HomeJavajavaTutorialDetailed explanation of MyBatis lazy loading example

Detailed explanation of MyBatis lazy loading example

Jun 25, 2017 am 10:38 AM
mybatisstudybuildgo deep

1. What is lazy loading

resultMap can achieve advanced mapping (using association and collection to achieve one-to-one and one-to-many mapping), association and collection have lazy loading function.

Requirements:

If you query orders and associate query user information. If we query the order information first, we can meet the requirements. When we need to query the user information, we can then check the user information. Querying user information on demand is lazy loading.

Lazy loading: Query from a single table first, and then perform related queries from related tables when needed, which greatly improves database performance, because querying a single table is faster than querying multiple tables in a related manner.

2. Use association to implement lazy loading

2.1 Requirements

Query orders and associate query user information

2.2mapper.xml

It is necessary to define the statements corresponding to the two mapper methods.

(1) Only query order information

SELECT * FROM orders

In the statement of query orderUse association to delay loading (execution) of the following statement ( Related query user information).

    <!-- 查询订单关联查询用户  --><select>SELECT * FROM orders</select>

(2) Query user information by association

Use the user_id in the order information queried above to query user information by association

Use FindUserById

    <select>select * from user where id=#{value}</select>

in UserMapper.xml first executes findOrdersUserLazyLoading, and then executes fingUserById when it is necessary to query the user. The lazy loading execution is configured through the definition of resultMap.

2.3 Delayed loading of resultMap

Use select in association to specify the id of the statement to be executed by delayed loading.

    <!-- 延迟加载的resultMap  --><resultmap><!-- 1.对订单信息进行映射配置 --><id></id><result></result><result></result><result></result><result></result><!-- 2.实现对用户信息进行延迟加载 --><!-- select:指定延迟加载需要执行的statement的id(是根据user_id查询用户信息的statement) 
               要使用UserMapper.xml中findUserById完成根据用户id(user_id)用户信息的查询,
               如果findUserById不在本mapper中需要前边加namespace。
             column:订单信息中关联用户信息查询的列,是user_id
              关联查询的sql理解为:
             SELECT orders.*,
                (SELECT username FROM USER WHERE orders.user_id = user.id)username,
                (SELECT sex FROM USER WHERE orders.user_id = user.id)sex
             FROM orders--><association></association></resultmap>

2.4mapper.java

    //查询订单关联查询用户,用户信息时延迟加载public List<orders> findOrdersUserLazyLoading() throws Exception;</orders>

2.5 Test

2.5.1 Test Idea

(1) Execute the above mapper method (findOrdersUserLazyLoading), and internally call findOrdersUserLazyLoading in joanna.yan.mybatis.mapper.OrdersCustomMapper to only query orders information (single table).

(2) In the program, traverse the List queried in the previous step. When we call getUser() in Orders, lazy loading begins.

(3) Delay loading and call the findUserById method in UserMapper.xml to obtain user information.

2.5.2 Delayed loading configuration

Mybatis does not enable delayed loading by default and needs to be configured in SqlMapConfig.xml.

Configure in the mybatis core configuration file:

lazyLoadingEnabled, aggressiveLazyLoading

##aggressiveLazyLoadingWhen set to 'true', lazy-loaded objects may be fully loaded with any lazy attributes. Otherwise, each property is loaded on demand. true | falsetrue## in SqlMapConfig.xml Medium configuration:
##Setting items

Description

Allowed values

Default value

lazyLoadingEnabled

Set lazy loading globally. If set to 'false', all associated ones will be loaded initially.

true | false

false

     <!-- 全局配置参数,需要时再设置  --> <settings> <!-- 打开延迟加载的开关  --> <setting></setting> <!-- 将积极加载改为消极加载即按需要加载 --> <setting></setting> </settings>

2.5.3 Test code
    @Testpublic void findOrdersUserLazyLoadingTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        OrdersCustomMapper ordersCustomMapper=sqlSession.getMapper(OrdersCustomMapper.class);
        List<orders> list=ordersCustomMapper.findOrdersUserLazyLoading();for (Orders orders : list) {//执行getUser()去查询用户信息,这里实现按需加载User user=orders.getUser();
            System.out.println(user);
        }
        sqlSession.close();
    }</orders>

2.6 Lazy loading thoughts
Do not use the association provided by mybatis And the lazy loading function in collection, how to implement lazy loading?

The implementation method is as follows:

Define two mapper methods:

(1) Query the order list

(2) Query user information based on user id

Implementation idea: First query the first mapper method and obtain the order information list

In the test program, call the second mapper method as needed to query user information.

In short, using the lazy loading method, first query simple SQL (preferably a single table, but also related queries), and then load other information of related queries as needed.

The above is the detailed content of Detailed explanation of MyBatis lazy loading example. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.