Home > Java > javaTutorial > body text

Detailed explanation of MyBatis lazy loading example

零下一度
Release: 2017-06-25 10:38:13
Original
1292 people have browsed it

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>
Copy after login

(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>
Copy after login

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>
Copy after login

2.4mapper.java

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

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 name="lazyLoadingEnabled" value="true"/> <!-- 将积极加载改为消极加载即按需要加载 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
Copy after login

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();
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!