Detailed explanation of MyBatis lazy loading example
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 id="findOrdersUserLazyLoading" resultMap="OrdersUserLazyLoadingResultMap">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 id="findUserById" parameterType="int" resultType="user">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 type="joanna.yan.mybatis.entity.Orders" id="OrdersUserLazyLoadingResultMap"><!-- 1.对订单信息进行映射配置 --><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="createtime" property="createtime"/><result column="note" property="note"/><!-- 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 property="user" javaType="joanna.yan.mybatis.entity.User"select="joanna.yan.mybatis.mapper.UserMapper.findUserById" column="user_id"></association></resultMap>
2.4mapper.java
//查询订单关联查询用户,用户信息时延迟加载public List<Orders> findOrdersUserLazyLoading() throws Exception;
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
(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
##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 |
When set to 'true', lazy-loaded objects may be fully loaded with any lazy attributes. Otherwise, each property is loaded on demand. | true | false | true |
<!-- 全局配置参数,需要时再设置 --> <settings> <!-- 打开延迟加载的开关 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 将积极加载改为消极加载即按需要加载 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
@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(); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

Title: Learn the main function in Go language from scratch. As a simple and efficient programming language, Go language is favored by developers. In the Go language, the main function is an entry function, and every Go program must contain the main function as the entry point of the program. This article will introduce how to learn the main function in Go language from scratch and provide specific code examples. 1. First, we need to install the Go language development environment. You can go to the official website (https://golang.org

Players can collect different materials to build buildings when playing in the Mistlock Kingdom. Many players want to know whether to build buildings in the wild. Buildings cannot be built in the wild in the Mistlock Kingdom. They must be within the scope of the altar. . Can buildings be built in the wild in Mistlock Kingdom? Answer: No. 1. Buildings cannot be built in the wild areas of the Mist Lock Kingdom. 2. The building must be built within the scope of the altar. 3. Players can place the Spirit Fire Altar by themselves, but once they leave the range, they will not be able to construct buildings. 4. We can also directly dig a hole in the mountain as our home, so we don’t need to consume building materials. 5. There is a comfort mechanism in the buildings built by players themselves, that is to say, the better the interior, the higher the comfort. 6. High comfort will bring attribute bonuses to players, such as

MyBatis is a popular persistence layer framework that provides convenient SQL mapping and database operation functions, allowing developers to interact with the database more efficiently. In the actual development process, we sometimes need to print out the SQL statements executed by MyBatis on the console in real time to better debug and optimize SQL queries. This article will introduce how to realize real-time printing of SQL on the console in MyBatis and provide specific code examples. First, we need to add My

PyTorch Installation Guide: Quickly set up a development environment in PyCharm PyTorch is one of the most popular frameworks in the current field of deep learning. It has the characteristics of ease of use and flexibility, and is favored by developers. This article will introduce how to quickly set up the PyTorch development environment in PyCharm, so that you can start the development of deep learning projects. Step 1: Install PyTorch First, we need to install PyTorch. The installation of PyTorch usually needs to take into account the system environment
