mybatis 延迟加载 代码示例
时间: 2023-11-07 09:06:11 浏览: 95
好的,关于mybatis延迟加载的代码示例,下面是一段示例代码:
```
public class User {
private Long id;
private String username;
private List<Order> orders;
// 省略构造方法和getter/setter方法
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
}
public interface UserMapper {
User selectUserById(Long id);
List<User> selectAllUsers();
}
public interface OrderMapper {
List<Order> selectOrdersByUserId(Long userId);
}
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectUserById(1L);
List<Order> orders = user.getOrders();
// 这里不会触发orders属性的延迟加载,因为已经通过selectUserById方法一并取出了
// 然后可以在需要使用orders属性的地方进行延迟加载
if (orders == null) {
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
orders = orderMapper.selectOrdersByUserId(user.getId());
user.setOrders(orders);
}
```
注:以上示例代码仅供参考,具体实现可能会因项目架构和需求不同而有所变化。
阅读全文