What is lazy-loading in MyBatis?

What is lazy-loading in MyBatis?

MyBatis' lazy-loading (lazy loading) is a data query strategy that allows associated data to be fetched from the database only when needed. This is accomplished by creating a Java proxy object that loads the related object into memory when it is actually needed.

For example, consider a system with two entity classes User and Role, and each user is assigned multiple roles. Then we can use the lazy loading mechanism to avoid the performance bottleneck caused by querying all role information at the same time when querying all user information.

The following is a specific introduction to the implementation of MyBatis lazy loading (Lazy Loading) based on a sample code:

public class User {
    
    
    private Long id;
    private String name;
    private List<Role> roleList;
    // getters 和 setters 略
}

public interface UserMapper {
    
    
   User getUserWithRoles(Long id); 
}

In the above code, each User object contains a role list field list. In order to avoid obtaining role information when querying, we can implement lazy loading in the following way:

  1. First, in the mapper.xml file, you need to configure the associated query SQL to load the Role information corresponding to the User object. As follows:
<select id="getUserWithRoles" resultMap="BaseResultMap">
    SELECT
        u.id,
        u.name,
        r.id as role_id,
        r.name as role_name
    FROM user u
    LEFT JOIN user_role ur ON u.id = ur.user_id
    LEFT JOIN role r ON ur.role_id = r.id
    WHERE u.id = #{id}
</select>

In this query statement, we use the JOIN method to aggregate the user table, user_role table, and role table and get all the data at once.

  1. Next, instead of loading the Role information directly when implementing the query, use the proxy class to load each Role object in the list. As follows:
public class User {
    
    
    // ...
    private List<Role> roleList;
    private transient SqlSession sqlSession;

    public List<Role> getRoleList() {
    
    
        if (sqlSession != null) {
    
    
            roleList = sqlSession.selectList("getUserRoles", id);
        }
        return roleList;
    }

    public void setSqlSession(SqlSession sqlSession) {
    
    
        this.sqlSession = sqlSession;
    }
}

As can be seen from the above code, whenever a user calls the getRoleList() method, it will check whether the target role list has been retrieved. If not, use a pre-defined SQL statement to perform lazy loading operations.

  1. In the UserMapper.xml file, write the SQL statement to obtain the Role information at the same time, and add an xml file parser to it in the mybatis-config.xml configuration file:
  <mapper resource="com/mybatis/xml/UserMapper.xml"/>

Thus, when querying for a single user, a User object is created and its getRoleList method is then handled by the proxy. When the getRoleList method is called for the first time, the agent sends a record query request and populates the wrapped List object, thus completing the lazy loading design.

Lazy loading can avoid unnecessary data reading and processing operations, thereby improving the performance and responsiveness of the program.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/131166888