How to handle lazy loading issue in MyBatis?
In MyBatis, performance issues can be addressed by utilizing lazy loading, which means fetching information from the database only when it is needed. MyBatis offers two ways to implement lazy loading.
- Lazy loading is used by configuring it in the mapping file of MyBatis. When querying the main object, the related object information is not retrieved immediately; it is only retrieved when the related object is needed. For example:
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="articles" ofType="Article" column="user_id" select="selectArticles" fetchType="lazy"/>
</resultMap>
- Utilizing a lazy loader: Configure a lazy loader in the MyBatis configuration file, then manually invoke it at the desired locations for lazy loading. For example:
User user = sqlSession.selectOne("selectUser", 1);
LazyLoader lazyLoader = new LazyLoader() {
@Override
public void load() {
user.setArticles(sqlSession.selectList("selectArticles", user.getId()));
}
};
user.setLazyLoader(lazyLoader);
By using lazy loading and delay loaders, the performance of queries can be improved by only retrieving information about associated objects when needed.