MyBatis supports lazy loading of associations and collections, which means that the related entities are not loaded from the database until they are accessed. This can be useful to improve performance and reduce memory usage in certain scenarios.

To configure lazy loading in MyBatis, you can use the lazyLoadingEnabled property in the MyBatis configuration file (mybatis-config.xml). Set this property to true to enable lazy loading.

Here is an example configuration for lazy loading:

<configuration>
  <settings>
    <setting name="lazyLoadingEnabled" value="true" />
  </settings>
  ...
</configuration>

In addition to enabling lazy loading globally, you can also control lazy loading on a per-relationship basis using the fetchType attribute in the mapping XML file. The fetchType attribute can have the values lazy or eager.

For example, suppose you have a User entity with a lazy-loaded orders collection:

<resultMap id="userResultMap" type="User">
  <id property="id" column="id" />
  <result property="name" column="name" />
  <collection property="orders" ofType="Order" fetchType="lazy">
    <id property="id" column="order_id" />
    <result property="amount" column="amount" />
  </collection>
</resultMap>

In this example, the orders collection will be lazily loaded when accessed.

Note that lazy loading requires an open database session. If the session is closed before accessing the lazy-loaded entities, an exception will be thrown

mybaits懒加载配置

原文地址: https://www.cveoy.top/t/topic/iL5X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录