springboot整合mybaits,采用延迟加载

一、概述
延迟加载:
在真正使用数据时才发起查询,不用的时候不查询。也叫按需加载,懒加载
立即加载:
不管用不用,只要一调用方法,马上发起查询。

在对应的四种表关系中:
一对一,多对一:通常情况下我们使用立即加载
一对多,多对多:通常情况下我们使用延迟加载

二、Springboot整合,采取延迟加载
1.首先,在配置文件上开启全局延迟加载
在这里插入图片描述
2.mapper映射文件
在这里插入图片描述
3.Pojo类
在这里插入图片描述
4.mapper类
在这里插入图片描述
5.service类
在这里插入图片描述
6.Controller类
在这里插入图片描述
7.执行方法,结果如下
在这里插入图片描述
8.在service中,我打印了实体类,正常是会触发延迟加载,但是我在配置文件中,取消了toString方法触发延迟加载,因此输出的employee为null。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个快速开发框架,MyBatis 是一款优秀的基于 Java 的持久层框架。在 Spring Boot 中使用 MyBatis 可以极大地提高开发效率和运行效率。 具体步骤如下: 1. 引入 MyBatis 和 MyBatis-SpringBoot-Starter 依赖。 2. 配置数据源和 MyBatis。 3. 编写实体类和映射文件。 4. 编写 DAO 层接口和 SQL 语句。 5. 在 Service 层中调用 DAO 层接口。 6. 在 Controller 层中调用 Service 层方法,返回结果给前端。 示例代码: 1. 引入依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> ``` 2. 配置数据源和 MyBatis: ``` spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root mybatis.mapper-locations=classpath:mapper/*.xml ``` 3. 编写实体类和映射文件: 实体类: ``` public class User { private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 映射文件: ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.example.demo.dao.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="age" property="age" /> </resultMap> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long"> select * from user where id = #{id} </select> </mapper> ``` 4. 编写 DAO 层接口和 SQL 语句: ``` public interface UserMapper { User selectByPrimaryKey(Long id); } ``` 5. 在 Service 层中调用 DAO 层接口: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectByPrimaryKey(id); } } ``` 6. 在 Controller 层中调用 Service 层方法,返回结果给前端: ``` @RestController public class UserController { @Autowired private UserService userService; @GetMapping(value = "/user/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值