Does mybatis support lazy loading in Java? What is the principle of lazy loading?

Yes, MyBatis supports lazy loading. Lazy loading refers to a technology that only loads its basic attributes when querying an object, and temporarily does not load the data of the associated object, and waits until the associated object is really needed to query and load its data.

  MyBatis enables lazy loading by configuring the lazyLoadingEnabled property in the mapping file.

  The principle is that when an object is queried, only the basic properties of the object are loaded, and for the associated object that is lazy loaded, only when it is really needed, by creating a proxy object, query and load its data to the database again.

  Here is the code demo:

  First, configure the lazyLoadingEnabled property in the MyBatis configuration file:

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

  Then, in the corresponding Mapper interface, use the @Results annotation to configure the associated objects for lazy loading:

@Results({
  @Result(property = "id", column = "id"),
  @Result(property = "name", column = "name"),
  @Result(property = "orders", javaType = List.class, column = "id",
          many = @Many(select = "com.example.mapper.OrderMapper.findByCustomerId", fetchType = FetchType.LAZY))
})
Customer findCustomerById(int id);

  In the above code, the Customer object contains the orders attribute, and the orders attribute needs to be lazy loaded, so configure fetchType = FetchType.LAZY in the @Results annotation.

  Finally, MyBatis automatically performs lazy loading when using associated objects:

Customer customer = customerMapper.findCustomerById(1);
List<Order> orders = customer.getOrders(); // 延迟加载,此时才会查询加载订单数据

  Lazy loading helps improve system performance because it reduces the number of queries to the database. However, it can also present some potential problems:

  1. Lazy loading will cause additional query operations, so if there are a lot of associated objects, lazy loading may lead to system performance degradation.

  2. If the lazy loaded object is modified or deleted in the external environment, data inconsistency may occur when loading the associated object. Therefore, when using lazy loading, it is necessary to ensure that the data of the associated object is stable.

  3. During lazy loading, MyBatis will create a proxy object to replace the real associated object, which may cause some problems, such as the inability to serialize the proxy object.

  Therefore, careful consideration is required when using lazy loading, weighing the performance benefits and potential problems it brings.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130391723